c++qtqjsengine

C++ QT Call C++ function in QJSEngine


I'm trying to call a function which is implemented in C++ to call in a JS function, which gets evaluated with the QT QJSEngine.

So far I have tried this

class Person : public QObject {

Q_OBJECT

public:
    Q_INVOKABLE cppFunction(int a);
    
};

My function evuation looks like this

QJSValue formulaFunction = jsEngine->evaluate("(function(" + functionArgList.join(",") + "){ " + formula + "})");

In formula I have a call to cppFunction and functionArgList provides the arguments, these work fine, I have checked them. So, but somehow it doesn't get called, I don't get an error too. Am I missing something or should it work this way?


Solution

  • So, after some research I got it running.

    class MyObject : public QObject{
    
       Q_OBJECT
    
    public:
        Q_INVOKABLE MyObject() {}
        Q_INVOKABLE bool hasChannel(int id);
    };
    
    QJSEngine engine;
        QJSValue injectedObject;
        injectedObject= engine.newQMetaObject(&MyObject::staticMetaObject);
        engine.globalObject().setProperty("MyObject", injectedObject);
    

    So, here I'm creating a new class which is inheriting from QObject. The class has two methods, every method I want to invoke in the QJSEngine has to provide the Q_INVOKABLE Label in front of the method declaration.

    An example JS code run by the engine would look like this

    let myObject = new MyObject();
    myObject.hasChannel(1234);
    

    I don't know if the injected prefix is appropriate, but I couldn't think of a better one