Qt offers a powerful feature that allows the seamless exposure of any C++ object to Javascript

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.

Answer №1

Because sqlfunctions is a subclass of QObject, it is possible to provide a sqlfunctions* object as an argument to a function that expects a QObject*:

frame->addToJavaScriptWindowObject(objJavascriptName, &obj);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Refreshing/Redrawing/Resizing a panel in jQuery Layout when toggling the visibility of a header or footer

Currently utilizing a standard jQuery layout with north, south, west, east, and center sections as outlined in the documentation. In both the west and center panels, there are header and footer panes included. While everything is functioning correctly, I ...

Capture the responseBody data within a Newman script from a Postman collection and save it to a

I'm trying to execute a script.js using newman with a locally saved postman collection. The call is successful in postman, returning a token in the response body that I need to access. I would prefer not to open postman every time just to get the res ...

Clicking on an anchor tag will open a div and change the background color

.nav_bar { background: #c30015; margin-left: 50px; float: left; } .nav_bar ul { padding: 0; margin: 0; display: flex; border-bottom: thin white solid; } .nav_bar ul li { list-style: none; } .nav_bar ul li a { ...

Error message: "The property is not found within the specified type when using the OR operator with

Within my Angular component, I am faced with a challenge involving an Input that can be one of two types. @Input() profile: UserProfileDetails | BusinessProfileDetails; The structure of the profile template is straightforward and I want to avoid duplicati ...

Techniques for Grouping an Array of Objects by a Specific Value Key in Angular

I have the following array that needs to be grouped by section_name in HTML. Additionally, I need to first check if the length of the array values for section_name is greater than zero before displaying the results grouped by section_name. I hope my expl ...

Enquire.js does not compute accurately at first glance, but only after adjustments are made during

Currently, I am working on incorporating media queries using Enquire.js and Vue.js. The functionality seems to be in good shape when manually resizing the browser window. However, upon loading the document, no match is detected. This peculiar behavior beco ...

Loading message displayed in web browsers by banner rotation system

I'm currently working on a banner rotator function that seems to be showing a "loading" message continuously while running. Here is the code snippet for reference: var banners = ['../Graphics/adv/1.gif','../Graphics/adv/2.jpg']; / ...

Enhancing the tooltip inner content in Bootstrap with a description:

Can you help me troubleshoot the code below? I am trying to add a description to numbers in my tooltip, but it doesn't seem to be working. Here is the HTML: <input id="contract-length" class="slider slider-step-2 slider-contract-length" ...

Switching picture using dropdown menu in javascript/jquery

Having some trouble trying to recreate this example. The initial image shows up, but it doesn't change when I select a different option. Still getting the hang of javascript so any help is appreciated. <html> <head> <script src="/j ...

Retrieving radio button value in Angular 2

Currently, I am attempting to retrieve the radio button value in an Angular 2 project. The radio buttons are defined in index.html as: <input type="radio" id="options1" name="function" value="create"> <input type="radio" id="options2" name="func ...

capturing the value of a button during the onChange event

I'm currently trying to retrieve the button value within an onChange event. My goal is to then bind this value to state, but unfortunately, I am receiving an empty value. <button onChange={this.handleCategoryName} onClick={this.goToNextPage}> ...

Creating an array of pointers to the base class and assigning objects of the derived class to it (Demonstrating polymorphism)

My Shape program is almost ready, but now I am working on implementing a menu. I have created all the shape classes, with two directly inheriting from the abstract class "Shape" and two others inheriting from a class called "Polygon," which in turn inherit ...

How long does jQuery animation last until completion?

Within my project, I am utilizing the animationComplete function from the jQuery mobile library. You can find this function at The animation in my project involves a sequence of objects with various tasks to be executed at each point of the animation. The ...

Enhancing the efficiency of the rendering process

My website project involves displaying a fish brain with numerous neurons, loaded as triangles and links from a database. While trying to render the models, I've encountered a performance issue that I suspect is related to how I'm handling the me ...

Easily accessing C++ object information within QML

In the process of developing a board game using Qt/C++ and qml, I am faced with the challenge of allowing qml sheets to access a single class containing all the essential game data. The goal is to have the qml sheets retrieve this data and display the game ...

Unlocking the Power of jQuery's toggle Method for Dynamic Functionality

For my project, I require numerous jQuery toggles to switch between text and icons. Currently, I am achieving this by using: $("#id1").click(function () { //Code for toggling display, changing icon and text }); $("#id2").click(function () { //Same co ...

What is the proper way to format parameters being sent to the server using JavaScript on the back end

Struggling to make the following code work in my ASP.NET demo application, looking for some guidance here. Check out the javascript code below: function checkUserName() { var request = createRequest(); if (request == null) { alert("Unable ...

What is the best way to configure Winston with Webpack?

I'm working on an electron application that utilizes node.js and I want to integrate the Winston logging library. After adding Winston to my package.json file, I encountered warnings from the colors.js dependency when running the webpack build command ...

Determine the quantity of modules within an active process

Is there a way to retrieve the total number of modules in a running process using its ID? Here is a function that can be used to fetch the total number of modules in a given process: int size(DWORD processID) { HMODULE hMods[1024]; HANDLE hProcess; DWOR ...

What's preventing the `@change` trigger from functioning properly with v-data-picker?

In my Vue.js application, I am utilizing the v-calendar package. I am trying to pass selected date range values to the parent component. However, why is the @change trigger not working? Parent.vue: <template> <div> <Child @set ...