I am interested in making a C++ object accessible from my class to Javascript.
Let me provide an example to better explain what I intend to do. In a specific project, I am working on creating a simple ShopApp.
So how can I achieve something like this (where mySqlObj
refers to my sqlfunctions
-object):
$(document).ready(function(){
$("#someButtonId").click(function(){
mySqlObj.refillBalance(1000); // adds 1000 units of money to user's account
// or
mySqlObj.listAllPorducts();
});
});
In this scenario, there is a class named sqlfunctions
. The contents of sqlfunctions.h
are as follows:
#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:
// Product Management
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();
// User Management
void registerUser(QString username, QString password);
void login(QString username, QString password);
void empowerUser();
void disempowerUser();
void listAllUsers();
void refillBalance(int amount);
private:
// Account Management
vector<product> cart;
bool isLogin;
bool isAdminLoggedIn;
int uid;
QSqlDatabase db;
};
#endif // SQLFUNCTIONS_H
My main.cpp
currently appears like this:
#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 reviewed the documentation and found information from this thread along with others like this, but some resources seem outdated leading to issues with compilation and building process.