I'd like to expose a C++ object from my own class to Javascript.
An example might clarify, what exactly I am trying to achieve. In a particular project I am trying to program some simple ShopApp.
So how can i make something like this possible (where mySqlObj
is my sqlfunctions
-object):
$(document).ready(function(){
$("#someButtonId").click(function(){
mySqlObj.refillBalance(1000); // adds 1000 units of money to user's account
// or
mySqlObj.listAllPorducts();
});
});
There I have got a class called sqlfunctions
. sqlfunctions.h
looks like this
#ifndef SQLFUNCTIONS_H
#define SQLFUNCTIONS_H
#include <iostream>
#include <vector>
#include <algorithm>
#include <QSqlQuery>
#include <QSql>
#include <QSqlDatabase>
#include <QDebug>
#include <QMessageBox>
#include <QObject>
#include <QString>
#include "product.h"
class product;
using namespace std;
typedef vector<product>::iterator iter;
class sqlfunctions:public QObject{
Q_OBJECT
public:
sqlfunctions();
signals:
void purchaseDone(vector<product> cart);
void adminLoggedIn();
public slots:
// Warenmanagement
product isAlreadyInCart(product myProduct);
void listAllProducts();
void addToCart(product myProduct);
void showCart();
void clearCart();
void changeAmount(product myProduct, string mode);
void changeAmount(product myProduct, int diff, string mode);
int checkStock();
double checkBalance();
void purchase();
// Usermanagement
void registerUser(QString username, QString password);
void login(QString username, QString password);
void empowerUser();
void disempowerUser();
void listAllUsers();
void refillBalance(int amount);
private:
// Accountmanagement
vector<product> cart;
bool isLogin;
bool isAdminLoggedIn;
int uid;
QSqlDatabase db;
};
#endif // SQLFUNCTIONS_H
My main.cpp
currently looks like the following:
#include <QApplication>
#include <QGraphicsWebView>
#include <QWebFrame>
#include <QtWebKit>
#include "html5applicationviewer.h"
#include "sqlfunctions.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
sqlfunctions obj;
Html5ApplicationViewer viewer;
viewer.setOrientation(Html5ApplicationViewer::ScreenOrientationAuto);
viewer.showExpanded();
viewer.loadFile(QLatin1String("src/index.html"));
viewer.setFixedSize(1200, 900);
QWebFrame *frame = viewer.webView()->page()->mainFrame();
QString objJavascriptName = "mySqlObj";
frame->addToJavaScriptWindowObject(objJavascriptName, &obj);
return app.exec();
}
I have considered the documentation and this thread (and some more like this one here), but the the SO-thread seems to be outdated, since that example does not compile and strange trouble with the building process/directory.