QJSEngine Class
The QJSEngine class runs JavaScript programs. More…
| Header | #include <QJSEngine> |
|---|---|
| CMake | target_link_libraries(app PRIVATE Nt::Qml) |
| Module | Nt Qml C++ Classes |
| Inherits | QObject |
| Inherited by | QQmlEngine |
List of all members, including inherited members
Public Types
| enum | ObjectOwnership |
| enum | Extension |
| typedef | Extensions |
Public Functions
| QJSEngine() | |
| QJSEngine(QObject *parent) | |
| ~QJSEngine() | |
| QJSValue | globalObject() const |
| QJSValue | evaluate(const QString &program, const QString &fileName = QString(), int lineNumber = 1, QStringList *exceptionStackTrace = nullptr) |
| QJSValue | importModule(const QString &fileName) |
| QJSValue | newObject() |
| QJSValue | newArray(uint length = 0) |
| QJSValue | newQObject(QObject *object) |
| QJSValue | newErrorObject(QJSValue::ErrorType errorType, const QString &message = QString()) |
| QJSValue | toScriptValue(const T &value) |
| T | fromScriptValue(const QJSValue &value) |
| void | collectGarbage() |
| void | installExtensions(Extensions extensions, const QJSValue &object = QJSValue()) |
| void | setInterrupted(bool interrupted) |
| bool | isInterrupted() const |
| void | throwError(const QString &message) |
| void | throwError(QJSValue::ErrorType errorType, const QString &message = QString()) |
| void | throwError(const QJSValue &error) |
| bool | hasError() const |
| QJSValue | catchError() |
| QString | uiLanguage() const |
| void | setUiLanguage(const QString &language) |
Signals
| void | uiLanguageChanged() |
Static Public Members
| void | setObjectOwnership(QObject *object, ObjectOwnership ownership) |
| ObjectOwnership | objectOwnership(QObject *object) |
Detailed Description
An engine has a global object, and evaluate() runs programs in it:
QJSEngine engine;
engine.installExtensions(QJSEngine::ConsoleExtension);
QJSValue result = engine.evaluate("[1, 2, 3].map(x => x * x).join(' + ')");
qDebug() << result.toString(); // "1 + 4 + 9"
QJSValue square = engine.evaluate("(function(x) { return x * x; })");
qDebug() << square.call({12}).toInt(); // 144
QJSValue error = engine.evaluate("undefinedFunction()", "inline.js");
if (error.isError())
qDebug() << "line" << error.property("lineNumber").toInt() << error.toString();
Values go both ways as QJSValue. A QObject passed to newQObject() is seen by scripts with its properties, its slots and Q_INVOKABLE methods, and its signals, which scripts connect to functions:
Counter counter;
engine.globalObject().setProperty("counter", engine.newQObject(&counter));
engine.evaluate(R"(
counter.valueChanged.connect(v => console.log("counter is now", v));
counter.value = 10;
counter.add(5);
)");
qDebug() << counter.value(); // 15
A script that throws makes evaluate() return the error; QJSValue::isError() tells. A C++ method that scripts call can throw a JavaScript error with throwError().
The language is ECMAScript 2017 without classes, generators, async functions, destructuring, symbols, Proxy and typed arrays; see Using Nt Qml for the details.
Source code is untrusted input: nesting, recursion and the size of arrays and strings are limited, so a script can fail but not crash the application. setInterrupted() stops a script that runs too long.
See also QJSValue and Using Nt Qml.
Differences from Qt
There is no importModule() (it returns an error), newSymbol(), newQMetaObject(), registerModule() or QJSManagedValue. JavaScript is interpreted, not compiled. Garbage is collected when no script runs. toScriptValue() and fromScriptValue() go through QVariant.
Member Type Documentation
enum QJSEngine::Extension
Optional parts of the global object.
| Constant | Description |
|---|---|
QJSEngine::TranslationExtension | qsTr(), qsTranslate() and the QT_TR_NOOP() family. Nt returns the text untranslated. |
QJSEngine::ConsoleExtension | console.log() and its siblings, and print(). |
QJSEngine::GarbageCollectionExtension | gc(). |
QJSEngine::AllExtensions | All of them. |
typedef QJSEngine::Extensions
A QFlags of Extension values.
enum QJSEngine::ObjectOwnership
Who deletes a QObject that scripts can see.
| Constant | Description |
|---|---|
QJSEngine::CppOwnership | C++ code does; the engine never does. |
QJSEngine::JavaScriptOwnership | The engine deletes it when no script can reach it any more, unless it has a parent. |
Member Function Documentation
QJSEngine::QJSEngine()
Constructs an engine with an empty global object, apart from the standard library.
QJSEngine::QJSEngine(QObject *parent)
Constructs an engine with the given parent.
QJSEngine::~QJSEngine()
Destroys the engine. QJSValues of the engine become undefined, and objects that scripts own are deleted.
QJSValue QJSEngine::catchError()
Returns the error that throwError() set and forgets it, or undefined if there is none.
void QJSEngine::collectGarbage()
Frees the objects that no script and no QJSValue can reach. It does nothing while a script runs.
QJSValue QJSEngine::evaluate(const QString &program, const QString &fileName = QString(), int lineNumber = 1, QStringList *exceptionStackTrace = nullptr)
Runs program, which comes from fileName at lineNumber, and returns the value of its last statement. If the program throws, returns the error, and if exceptionStackTrace is not nullptr, stores the functions that were running, innermost first, as name@file:line.
QJSEngine engine;
engine.installExtensions(QJSEngine::ConsoleExtension);
QJSValue result = engine.evaluate("[1, 2, 3].map(x => x * x).join(' + ')");
qDebug() << result.toString(); // "1 + 4 + 9"
QJSValue square = engine.evaluate("(function(x) { return x * x; })");
qDebug() << square.call({12}).toInt(); // 144
QJSValue error = engine.evaluate("undefinedFunction()", "inline.js");
if (error.isError())
qDebug() << "line" << error.property("lineNumber").toInt() << error.toString();
template <typename T>T QJSEngine::fromScriptValue(const QJSValue &value)
Returns value converted to T through QVariant.
QJSValue QJSEngine::globalObject() const
Returns the global object, where scripts find the standard library and the names they declare.
bool QJSEngine::hasError() const
Returns true if throwError() was called and the error was not yet thrown or caught; otherwise returns false.
QJSValue QJSEngine::importModule(const QString &fileName)
Returns an error: modules are not supported. fileName is not used.
void QJSEngine::installExtensions(Extensions extensions, const QJSValue &object = QJSValue())
Adds the extensions to object, or to the global object if object is undefined.
bool QJSEngine::isInterrupted() const
Returns true if scripts are interrupted; otherwise returns false.
QJSValue QJSEngine::newArray(uint length = 0)
Returns a new array of length undefined elements.
QJSValue QJSEngine::newErrorObject(QJSValue::ErrorType errorType, const QString &message = QString())
Returns a new error of the given errorType with message.
QJSValue QJSEngine::newObject()
Returns a new, empty object.
QJSValue QJSEngine::newQObject(QObject *object)
Returns object as scripts see it: its properties, slots, invokable methods and signals. The same object always gives the same value. If object has no parent and its ownership was not set with setObjectOwnership(), the engine owns it and deletes it when no script can reach it.
ObjectOwnership QJSEngine::objectOwnership(QObject *object)
Returns who deletes object: the ownership set with setObjectOwnership(), or JavaScriptOwnership for an object without a parent and CppOwnership for one with a parent.
void QJSEngine::setInterrupted(bool interrupted)
Stops running scripts if interrupted is true: the next statement throws an error. While it is set, no script runs. Call it from another thread to stop a script that runs too long.
void QJSEngine::setObjectOwnership(QObject *object, ObjectOwnership ownership)
Sets who deletes object to ownership, for the engines that see it.
void QJSEngine::setUiLanguage(const QString &language)
Sets the language of the user interface to language. Nt keeps it for scripts and QML.
void QJSEngine::throwError(const QString &message)
Throws an Error with message in the script that called the running C++ method.
void QJSEngine::throwError(QJSValue::ErrorType errorType, const QString &message = QString())
This is an overloaded function.
Throws an error of the given errorType with message.
void QJSEngine::throwError(const QJSValue &error)
This is an overloaded function.
Throws error, which may be any value.
template <typename T>QJSValue QJSEngine::toScriptValue(const T &value)
Returns value as a script value, converted through QVariant.
QString QJSEngine::uiLanguage() const
Returns the language of the user interface, empty by default.
void QJSEngine::uiLanguageChanged()
This signal is emitted when the language of the user interface changes.
See also setUiLanguage().