QJSEngine Class

The QJSEngine class provides an environment for evaluating JavaScript code. More...

Header: #include <QJSEngine>
qmake: QT += qml
Since: Qt 5.0
Inherits: QObject
Inherited By:

QQmlEngine

This class was introduced in Qt 5.0.

Note: All functions in this class are reentrant.

Public Types

enum Extension { TranslationExtension, ConsoleExtension, GarbageCollectionExtension, AllExtensions }

Properties

Public Functions

void setUiLanguage(const QString &language)
QString uiLanguage() const

Signals

Detailed Description

Evaluating Scripts

Use evaluate() to evaluate script code.

 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():

 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():

 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:

 export function sum(left, right)
 {
     return left + right
 }

This module can be loaded with QJSEngine::import() if it is saved under the name math.mjs:

 QJSvalue module = myEngine.importModule("./math.mjs");
 QJSValue sumFunction = module.property("sum");
 QJSValue result = sumFunction.call(args);

Modules can also use functionality from other modules using import statements:

 import { sum } from "./math.mjs";
 export function addTwice(left, right)
 {
     return sum(left, right) * 2;
 }

Engine Configuration

The globalObject() function returns the Global Object associated with the script engine. Properties of the Global Object are accessible from any script code (i.e. they are global variables). Typically, before evaluating "user" scripts, you will want to configure a script engine by adding one or more properties to the Global Object:

 myEngine.globalObject().setProperty("myNumber", 123);
 ...
 QJSValue myNumberPlusOne = myEngine.evaluate("myNumber + 1");

Adding custom properties to the scripting environment is one of the standard means of providing a scripting API that is specific to your application. Usually these custom properties are objects created by the newQObject() or newObject() functions.

Script Exceptions

evaluate() can throw a script exception (e.g. due to a syntax error). If it does, then evaluate() returns the value that was thrown (typically an Error object). Use QJSValue::isError() to check for exceptions.

For detailed information about the error, use QJSValue::toString() to obtain an error message, and use QJSValue::property() to query the properties of the Error object. The following properties are available:

  • name
  • message
  • fileName
  • lineNumber
  • stack
 QJSValue result = myEngine.evaluate(...);
 if (result.isError())
     qDebug()
             << "Uncaught exception at line"
             << result.property("lineNumber").toInt()
             << ":" << result.toString();

Script Object Creation

Use newObject() to create a JavaScript object; this is the C++ equivalent of the script statement new Object(). You can use the object-specific functionality in QJSValue to manipulate the script object (e.g. QJSValue::setProperty()). Similarly, use newArray() to create a JavaScript array object.

QObject Integration

Use newQObject() to wrap a QObject (or subclass) pointer. newQObject() returns a proxy script object; properties, children, and signals and slots of the QObject are available as properties of the proxy object. No binding code is needed because it is done dynamically using the Qt meta object system.

 QPushButton *button = new QPushButton;
 QJSValue scriptButton = myEngine.newQObject(button);
 myEngine.globalObject().setProperty("button", scriptButton);

 myEngine.evaluate("button.checkable = true");

 qDebug() << scriptButton.property("checkable").toBool();
 scriptButton.property("show").call(); // call the show() slot

Use newQMetaObject() to wrap a QMetaObject; this gives you a "script representation" of a QObject-based class. newQMetaObject() returns a proxy script object; enum values of the class are available as properties of the proxy object.

Constructors exposed to the meta-object system (using Q_INVOKABLE) can be called from the script to create a new QObject instance with JavaScriptOwnership. For example, given the following class definition:

 class MyObject : public QObject
 {
     Q_OBJECT

 public:
     Q_INVOKABLE MyObject() {}
 };

The staticMetaObject for the class can be exposed to JavaScript like so:

 QJSValue jsMetaObject = engine.newQMetaObject(&MyObject::staticMetaObject);
 engine.globalObject().setProperty("MyObject", jsMetaObject);

Instances of the class can then be created in JavaScript:

 engine.evaluate("var myObject = new MyObject()");

Note: Currently only classes using the Q_OBJECT macro are supported; it is not possible to expose the staticMetaObject of a Q_GADGET class to JavaScript.

Dynamic QObject Properties

Dynamic QObject properties are not supported. For example, the following code will not work:

 QJSEngine engine;

 QObject *myQObject = new QObject();
 myQObject->setProperty("dynamicProperty", 3);

 QJSValue myScriptQObject = engine.newQObject(myQObject);
 engine.globalObject().setProperty("myObject", myScriptQObject);

 qDebug() << engine.evaluate("myObject.dynamicProperty").toInt();

Extensions

QJSEngine provides a compliant ECMAScript implementation. By default, familiar utilities like logging are not available, but they can can be installed via the installExtensions() function.

See also QJSValue, Making Applications Scriptable, and List of JavaScript Objects and Functions.

Member Type Documentation

enum QJSEngine::Extension

This enum is used to specify extensions to be installed via installExtensions().

ConstantValueDescription
QJSEngine::TranslationExtension0x1Indicates that translation functions (qsTr(), for example) should be installed. This also installs the Qt.uiLanguage property.
QJSEngine::ConsoleExtension0x2Indicates that console functions (console.log(), for example) should be installed.
QJSEngine::GarbageCollectionExtension0x4Indicates that garbage collection functions (gc(), for example) should be installed.
QJSEngine::AllExtensions0xffffffffIndicates that all extension should be installed.

TranslationExtension

The relation between script translation functions and C++ translation functions is described in the following table:

Script FunctionCorresponding C++ Function
qsTr()QObject::tr()
QT_TR_NOOP()QT_TR_NOOP()
qsTranslate()QCoreApplication::translate()
QT_TRANSLATE_NOOP()QT_TRANSLATE_NOOP()
qsTrId()qtTrId()
QT_TRID_NOOP()QT_TRID_NOOP()

This flag also adds an arg() function to the string prototype.

For more information, see the Internationalization with Qt documentation.

ConsoleExtension

The console object implements a subset of the Console API, which provides familiar logging functions, such as console.log().

The list of functions added is as follows:

  • console.assert()
  • console.debug()
  • console.exception()
  • console.info()
  • console.log() (equivalent to console.debug())
  • console.error()
  • console.time()
  • console.timeEnd()
  • console.trace()
  • console.count()
  • console.warn()
  • print() (equivalent to console.debug())

For more information, see the Console API documentation.

GarbageCollectionExtension

The gc() function is equivalent to calling collectGarbage().

Property Documentation

uiLanguage : QString

This property holds the language to be used for translating user interface strings

This property holds the name of the language to be used for user interface string translations. It is exposed for reading and writing as Qt.uiLanguage when the QJSEngine::TranslationExtension is installed on the engine. It is always exposed in instances of QQmlEngine.

You can set the value freely and use it in bindings. It is recommended to set it after installing translators in your application. By convention, an empty string means no translation from the language used in the source code is intended to occur.

This property was introduced in Qt 5.15.

Access functions:

QString uiLanguage() const
void setUiLanguage(const QString &language)

Notifier signal:

void uiLanguageChanged()