Passing arguments to the QJSEngine



  • I am trying to pass a list of arguments to a javascript function via the QJSEngine.
    The following code will display "The passed amount of arguments is 15" i.e. the length of the first argument passed - looking further I can see that args[0] contains "M", args[1] contains "Y", args[2] contains "F",....,args[15] contains "T" while I was awaiting something like "The passed amount of arguments is 3" where args[0] contains "MYFIRSTARGUMENT", args[1] contains "A", args[2] contains "B".

    QJSValueList args;
    args << "MYFIRSTARGUMENT";
    args << "A";
    args << "B";
    
    QJSValue fun = m_jsEngine->evaluate("(function(args) { return args.length; })");
    QJSValue result = fun.call(args);
    qDebug() << QString("The passed amount of arguments is %1").arg(result.toInt());


  • @Lolo67
    Where does the documentation actually define QJSValueList? I see it used at http://doc.qt.io/qt-5/qjsvalue.html#call

    QJSValue QJSValue::call(const QJSValueList &args = QJSValueList())

    but it's not a hyperlink.


  • Lifetime Qt Champion

    It's a typedef of QList<QJSValue>


  • Qt Champions 2016

    Hi
    Im have not used this class so this is only a note.
    The doc sample seems to have extra parameter to the call function which seems to
    relate to your issue that only the first value of the list is used for arg.

    Doc sample

    QJSValue fun = myEngine.evaluate("(function(a, b) { return a + b; })");
    QJSValueList args;
    args << 1 << 2;
    QJSValue threeAgain = fun.call(QJSValue(), args);
    

    However the call is defined as
    QJSValue QJSValue::call(const QJSValueList & args = QJSValueList())

    So maybe sample is just wrong.


  • Lifetime Qt Champion

    A documentation fix is on its way.

    If you remove the QJSValue() from the parameters, the example works as expected.


  • Qt Champions 2016

    Hi
    Ok, rare case of wrong docs :)

    So the reason that the OPs code is not working is that he need to specify the parameters separately and
    the arg is not/ cannot be used as a list ?
    like
    m_jsEngine->evaluate("(function(a1,a2, a3) { })");



  • By the way the same effect can be observed when using QScriptEngine

    QScriptEngine *m_ScriptEngine = new QScriptEngine(this);
    QScriptValueList scriptArgs;
    scriptArgs << "MYFIRSTARGUMENT";
    scriptArgs << "A";
    scriptArgs << "B";
    
    QScriptValue  fun = m_ScriptEngine->evaluate("(function(args) { return args.length; })");
    QScriptValue  result = fun.call(QScriptValue(), scriptArgs);
    qDebug() << QString("The passed amount of arguments is %1").arg(result.toInt32());
    delete m_ScriptEngine;

Log in to reply
 

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