Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

C++ callback in JS using QScriptValue



  • Hi,
    I can call JS function with arguments and get the result using QScriptValue but question is: how to send an argument as a C++ callback?

    My JS script:

    function test(testCallback)
    {
       testCallback(5);
    }
    

    And my callback (C++):

    void Test::testCallback(const qint32& value)
    {
    // Signal and other actions
    emit testSignal(value);
    // ...
    }
    

    Application won't use qml, but inherits some js functions from another project.



  • Hi,
    You can send C++ callback function as an argument. Firstly, use QScriptEngine globalObject method to get QObject callback (your testCallback) and then use your test function with testCallback parameter.

        QScriptValue global = engine.globalObject();
        QScriptValue testCallback = global.property("Test").property("testCallback");
        QScriptValue test = global.property("test");
        QScriptValueList vals;
        vals<<testCallback<<23;
        QScriptValue result = test.call(global,vals);
        qDebug()<<"result : "<<result.toInt32()<<endl;
       
    
    
        
    

Log in to reply