[Solved]Call function in script



  • I am trying to make an application which shows and let you edit some data. Currently, I am trying to integrate custom logic into the application where the user can execute custom code during runtime. I am using QJSEngine for this since QScriptEngine is deprecated.

    I evaluate and run the script in my class CustomCode like so:

    void CustomCode::on_button_clicked()
    {
        QLabel *tb = new QLabel;
        ui->verticalLayout->addWidget(tb);
        QJSEngine myEngine;
        QJSValue scripttb = myEngine.newQObject(tb);
    
        QJSValue jsfunctionObj = myEngine.newQObject(&jsfunction);
        myEngine.globalObject().setProperty("jsfunction",jsfunctionObj);
        myEngine.globalObject().setProperty("tb",scripttb);
    
    
        QString fileName = "customlogic.qs";
        QFile scriptFile(fileName);
        if (!scriptFile.open(QIODevice::ReadOnly))
        {
        }// handle error
    
        QTextStream stream(&scriptFile);
        QString contents = stream.readAll();
        scriptFile.close();
        QJSValue result = myEngine.evaluate(contents, fileName);
        //QJSValue result = myEngine.evaluate("jsfunction.call_test();");
        if (result.isError())
        {
            qDebug() << "result: " << result.property("lineNumber").toInt() << ":" << result.toString();
        }
    }
    

    this was tested and works. Now, what I want to do is access functions in my mainwindow via the script and being able to call functions inside the script from my mainwindow (when a parameter changes the script has to process new data). Would it be possible to connect a signal/slot from mainwindow to a function inside the script and vice versa? (I think I have the calling of a function of mainwindow from inside the script working correctly but I would like to see my other options as well)

    thanks!



  • I managed using the following additional lines in CustomCode

    QString function = "test(1)";
    QJSValue testfunction = myEngine.evaluate(function);
    qDebug() << testfunction.toString();
    

    With my script CustomLogic.qs looking like this:

    function test(x)
    {
        var a = "tested!";
        a = a + x.toString();
        return a;
    }
    

    Returns "tested!1" in the application output



Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.