Evaluate JavaScript from Qt source



  • Hi Folks,

    can anybody explain me, how I can execute javascript from a command line application? As I saw, some QWebWidget or something like that is needed on some UI interface.
    My problem is that I would like to put some algorithm into separated javascript file due to portability and evaluate it, but I don't like any UI.

    Regards,
    Norbert


  • Moderators

    You can evaluate it using QtScript module.



  • Hi,

    thank you fort the short reply. I tried out, without too much success. I have the following sample JS function in separated file:

    .pragma library
    function func() {
        return 2 * 8;
    }
    

    and the following C++ code:

        QFile scriptFile("://compiler.js");
        scriptFile.open(QIODevice::ReadOnly);
        QString script(scriptFile.readAll());
        scriptFile.close();
    
        qDebug() << script;
    
        QScriptEngine myEngine;
        QScriptValue retVal = myEngine.evaluate(script, "://compiler.js");
        qDebug() << retVal.toString();
    

    but I'm getting the error: "SyntaxError: Parse error". Could you point me, what did I wrong?

    Regards,
    Norbert

    p.s.: sorry for the wrong highlight, I'm new to this forum design.


  • Moderators

    I have not used QtScript myself, sorry. One thing that might help is to open the file in this mode: QFile::ReadOnly | QFile::Text


  • Moderators

    Hi @moravas,

    .pragma library

    is QML-only syntax. You can't use this with Qt Script.



  • Hi,

    thank you for the help, it solved the issue. The result is "undefined" now. I don't udnerstand, but I think, it's regarding to another topic.

    Regards.


  • Moderators

    The result is undefined now, because your javascript contains only a function definition. Everything works fine and undefined is the correct result. If you want to receive something else, try for example:

    function func() {
    return 2 * 8;
    }
    func() // actually call func() 
    

Log in to reply
 

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