QJSEngine Class

  • Header: QJSEngine

  • Since: Qt 5.0

  • CMake:

    find_package(Qt6 REQUIRED COMPONENTS Qml)

    target_link_libraries(mytarget PRIVATE Qt6::Qml)

  • qmake: QT += qml

  • Inherits: QObject

  • Inherited By: QQmlEngine

  • Group: QJSEngine is part of qtjavascript

Detailed Description

 

Evaluating Scripts

Use evaluate() to evaluate script code.

 
Sélectionnez
QJSEngine myEngine;
QJSValue three = myEngine.evaluate("1 + 2");

evaluate() returns a QJSValue that holds the result of the evaluation. The QJSValue class provides functions for converting the result to various C++ types (e.g. QJSValue::toString() and QJSValue::toNumber()).

The following code snippet shows how a script function can be defined and then invoked from C++ using QJSValue::call():

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

As can be seen from the above snippets, a script is provided to the engine in the form of a string. One common way of loading scripts is by reading the contents of a file and passing it to evaluate():

 
Sélectionnez
QString fileName = "helloworld.qs";
QFile scriptFile(fileName);
if (!scriptFile.open(QIODevice::ReadOnly))
    // handle error
QTextStream stream(&scriptFile);
QString contents = stream.readAll();
scriptFile.close();
myEngine.evaluate(contents, fileName);

Here we pass the name of the file as the second argument to evaluate(). This does not affect evaluation in any way; the second argument is a general-purpose string that is stored in the Error object for debugging purposes.

For larger pieces of functionality, you may want to encapsulate your code and data into modules. A module is a file that contains script code, variables, etc., and uses export statements to describe its interface towards the rest of the application. With the help of import statements, a module can refer to functionality from other modules. This allows building a scripted application from smaller connected building blocks in a safe way. In contrast, the approach of using evaluate() carries the risk that internal variables or functions from one evaluate() call accidentally pollute the global object and affect subsequent evaluations.

The following example provides a module that can add numbers:

 
Sélectionnez
export