QJSEngine 类

The QJSEngine class provides an environment for evaluating JavaScript code. 更多...

头: #include <QJSEngine>
qmake: QT += qml
Since: Qt 5.0
继承: QObject
继承者: QQmlEngine

注意: 此类的所有函数 可重入 .

公共类型

enum Extension { TranslationExtension, ConsoleExtension, GarbageCollectionExtension, AllExtensions }
flags 扩展

公共函数

QJSEngine ()
QJSEngine (QObject * parent )
virtual ~QJSEngine ()
void collectGarbage ()
QJSValue evaluate (const QString & program , const QString & fileName = QString(), int lineNumber = 1)
T fromScriptValue (const QJSValue & value )
QJSValue globalObject () const
void installExtensions (Extensions extensions , const QJSValue & object = QJSValue())
QJSValue newArray (uint length = 0)
QJSValue newObject ()
QJSValue newQMetaObject (const QMetaObject * metaObject )
QJSValue newQMetaObject ()
QJSValue newQObject (QObject * object )
QJSValue toScriptValue (const T & value )
QJSEngine * qjsEngine (const QObject * object )

额外继承成员

详细描述

The QJSEngine class provides an environment for evaluating JavaScript code.

估算脚本

使用 evaluate () to evaluate script code.

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

evaluate () 返回 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 () 和 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.

引擎配置

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 () 或 newObject () 函数。

脚本异常

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:

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

脚本对象的创建

使用 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 集成

使用 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
					

使用 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()");
					

注意: Currently only classes using the Q_OBJECT macro are supported; it is not possible to expose the staticMetaObject 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();
					

扩展

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

另请参阅 QJSValue , Making Applications Scriptable ,和 List of JavaScript Objects and Functions .

成员类型文档编制

enum QJSEngine:: Extension
flags QJSEngine:: 扩展

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

常量 描述
QJSEngine::TranslationExtension 0x1 Indicates that translation functions ( qsTr() , for example) should be installed.
QJSEngine::ConsoleExtension 0x2 Indicates that console functions ( console.log() , for example) should be installed.
QJSEngine::GarbageCollectionExtension 0x4 Indicates that garbage collection functions ( gc() , for example) should be installed.
QJSEngine::AllExtensions 0xffffffff Indicates that all extension should be installed.

TranslationExtension

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

Script Function Corresponding 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.

更多信息,见 Qt 国际化 文档编制。

ConsoleExtension

The console object implements a subset of the 控制台 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() )

更多信息,见 控制台 API 文档编制。

GarbageCollectionExtension

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

The Extensions type is a typedef for QFlags <Extension>. It stores an OR combination of Extension values.

成员函数文档编制

QJSEngine:: QJSEngine ()

构造 QJSEngine 对象。

The globalObject () is initialized to have properties as described in ECMA-262 , Section 15.1.

QJSEngine:: QJSEngine ( QObject * parent )

构造 QJSEngine 对象采用给定 parent .

The globalObject () is initialized to have properties as described in ECMA-262 , Section 15.1.

[虚拟] QJSEngine:: ~QJSEngine ()

销毁此 QJSEngine .

Garbage is not collected from the persistent JS heap during QJSEngine destruction. If you need all memory freed, call collectGarbage manually right before destroying the QJSEngine .

void QJSEngine:: collectGarbage ()

Runs the garbage collector.

The garbage collector will attempt to reclaim memory by locating and disposing of objects that are no longer reachable in the script environment.

Normally you don't need to call this function; the garbage collector will automatically be invoked when the QJSEngine decides that it's wise to do so (i.e. when a certain number of new objects have been created). However, you can call this function to explicitly request that garbage collection should be performed as soon as possible.

QJSValue QJSEngine:: evaluate (const QString & program , const QString & fileName = QString(), int lineNumber = 1)

Evaluates program ,使用 lineNumber as the base line number, and returns the result of the evaluation.

The script code will be evaluated in the context of the global object.

The evaluation of program can cause an exception in the engine; in this case the return value will be the exception that was thrown (typically an Error object; see QJSValue::isError ()).

lineNumber is used to specify a starting line number for program ; line number information reported by the engine that pertains to this evaluation will be based on this argument. For example, if program consists of two lines of code, and the statement on the second line causes a script exception, the exception line number would be lineNumber plus one. When no starting line number is specified, line numbers will be 1-based.

fileName is used for error reporting. For example, in error objects the file name is accessible through the "fileName" property if it is provided with this function.

注意: If an exception was thrown and the exception value is not an Error instance (i.e., QJSValue::isError () 返回 false ), the exception value will still be returned, but there is currently no API for detecting that an exception did occur in this case.

T QJSEngine:: fromScriptValue (const QJSValue & value )

返回给定 value 被转换成模板类型 T .

另请参阅 toScriptValue ().

QJSValue QJSEngine:: globalObject () const

Returns this engine's Global Object.

By default, the Global Object contains the built-in objects that are part of ECMA-262 , such as Math, Date and String. Additionally, you can set properties of the Global Object to make your own extensions available to all script code. Non-local variables in script code will be created as properties of the Global Object, as well as local variables in global code.

void QJSEngine:: installExtensions ( 扩展 extensions , const QJSValue & object = QJSValue())

Installs JavaScript extensions to add functionality that is not available in a standard ECMAScript implementation.

The extensions are installed on the given object , or on the Global Object if no object is specified.

Several extensions can be installed at once by OR -ing the enum values:

installExtensions(QJSEngine::TranslationExtension | QJSEngine::ConsoleExtension);
					

该函数在 Qt 5.6 引入。

另请参阅 Extension .

QJSValue QJSEngine:: newArray ( uint length = 0)

Creates a JavaScript object of class Array with the given length .

另请参阅 newObject ().

QJSValue QJSEngine:: newObject ()

Creates a JavaScript object of class Object.

The prototype of the created object will be the Object prototype object.

另请参阅 newArray () 和 QJSValue::setProperty ().

QJSValue QJSEngine:: newQMetaObject (const QMetaObject * metaObject )

Creates a JavaScript object that wraps the given QMetaObject The metaObject must outlive the script engine. It is recommended to only use this method with static metaobjects.

When called as a constructor, a new instance of the class will be created. Only constructors exposed by Q_INVOKABLE will be visible from the script engine.

该函数在 Qt 5.8 引入。

另请参阅 newQObject () 和 QObject 集成 .

QJSValue QJSEngine:: newQMetaObject ()

Creates a JavaScript object that wraps the static QMetaObject associated with class T .

该函数在 Qt 5.8 引入。

另请参阅 newQObject () 和 QObject 集成 .

QJSValue QJSEngine:: newQObject ( QObject * object )

Creates a JavaScript object that wraps the given QObject object , using JavaScriptOwnership.

Signals and slots, properties and children of object are available as properties of the created QJSValue .

object is a null pointer, this function returns a null value.

If a default prototype has been registered for the object 's class (or its superclass, recursively), the prototype of the new script object will be set to be that default prototype.

若给定 object is deleted outside of the engine's control, any attempt to access the deleted QObject 's members through the JavaScript wrapper object (either by script code or C++) will result in a script exception .

另请参阅 QJSValue::toQObject ().

QJSValue QJSEngine:: toScriptValue (const T & value )

创建 QJSValue 采用给定 value .

另请参阅 fromScriptValue ().

相关非成员

QJSEngine * qjsEngine (const QObject * object )

返回 QJSEngine associated with object ,若有的话。

This function is useful if you have exposed a QObject to the JavaScript environment and later in your program would like to regain access. It does not require you to keep the wrapper around that was returned from QJSEngine::newQObject ().

该函数在 Qt 5.5 引入。