QJSEngine 类提供用于估算 JavaScript 代码的环境。 更多...
头: | #include <QJSEngine> |
CMake: |
find_package(Qt6 REQUIRED COMPONENTS Qml)
target_link_libraries(mytarget PRIVATE Qt6::Qml) |
qmake: | QT += qml |
继承: | QObject |
继承者: | QQmlEngine |
注意: 此类的所有函数 可重入 .
enum | Extension { TranslationExtension, ConsoleExtension, GarbageCollectionExtension, AllExtensions } |
flags | 扩展 |
enum | ObjectOwnership { CppOwnership, JavaScriptOwnership } |
QJSEngine () | |
QJSEngine (QObject * parent ) | |
virtual | ~QJSEngine () override |
QJSValue | catchError () |
To | coerceValue (const From & from ) |
void | collectGarbage () |
QJSValue | evaluate (const QString & program , const QString & fileName = QString(), int lineNumber = 1, QStringList * exceptionStackTrace = nullptr) |
T | fromManagedValue (const QJSManagedValue & value ) |
T | fromPrimitiveValue (const QJSPrimitiveValue & value ) |
T | fromScriptValue (const QJSValue & value ) |
T | fromVariant (const QVariant & value ) |
QJSValue | globalObject () const |
bool | hasError () const |
QJSValue | importModule (const QString & fileName ) |
void | installExtensions (QJSEngine::Extensions extensions , const QJSValue & object = QJSValue()) |
bool | isInterrupted () const |
QJSValue | newArray (uint length = 0) |
QJSValue | newErrorObject (QJSValue::ErrorType errorType , const QString & message = QString()) |
QJSValue | newObject () |
QJSValue | newQMetaObject (const QMetaObject * metaObject ) |
QJSValue | newQMetaObject () |
QJSValue | newQObject (QObject * object ) |
QJSValue | newSymbol (const QString & name ) |
bool | registerModule (const QString & moduleName , const QJSValue & value ) |
void | setInterrupted (bool interrupted ) |
void | setUiLanguage (const QString & 语言 ) |
void | throwError (const QString & message ) |
void | throwError (QJSValue::ErrorType errorType , const QString & message = QString()) |
void | throwError (const QJSValue & error ) |
QJSManagedValue | toManagedValue (const T & value ) |
QJSPrimitiveValue | toPrimitiveValue (const T & value ) |
QJSValue | toScriptValue (const T & value ) |
QString | uiLanguage () const |
void | uiLanguageChanged () |
QJSEngine::ObjectOwnership | objectOwnership (QObject * object ) |
void | setObjectOwnership (QObject * object , QJSEngine::ObjectOwnership ownership ) |
QJSEngine * | qjsEngine (const QObject * object ) |
使用 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.
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; }
Modules don't have to be files. They can be values registered with QJSEngine::registerModule ():
import version from "version"; export function getVersion() { return version; }
QJSValue version(610); myEngine.registerModule("version", version); QJSValue module = myEngine.importModule("./myprint.mjs"); QJSValue getVersion = module.property("getVersion"); QJSValue result = getVersion.call();
Named exports are supported, but because they are treated as members of an object, the default export must be an ECMAScript object. Most of the newXYZ functions in QJSValue will return an object.
QJSValue name("Qt6"); QJSValue obj = myEngine.newObject(); obj.setProperty("name", name); myEngine.registerModule("info", obj);
import { name } from "info"; export function getName() { return name; }
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.
使用 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 实例与 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 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 be installed via the installExtensions () 函数。
另请参阅 QJSValue , Making Applications Scriptable ,和 List of JavaScript Objects and Functions .
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. This also installs the Qt.
uiLanguage
特性。
|
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.
ObjectOwnership controls whether or not the JavaScript memory manager automatically destroys the QObject when the corresponding JavaScript object is garbage collected by the engine. The two ownership options are:
常量 | 值 | 描述 |
---|---|---|
QJSEngine::CppOwnership
|
0
|
The object is owned by C++ code and the JavaScript memory manager will never delete it. The JavaScript destroy() method cannot be used on these objects. This option is similar to QScriptEngine::QtOwnership. |
QJSEngine::JavaScriptOwnership
|
1
|
The object is owned by JavaScript. When the object is returned to the JavaScript memory manager as the return value of a method call, the JavaScript memory manager will track it and delete it if there are no remaining JavaScript references to it and it has no QObject::parent (). An object tracked by one QJSEngine will be deleted during that QJSEngine 's destructor. Thus, JavaScript references between objects with JavaScriptOwnership from two different engines will not be valid if one of these engines is deleted. This option is similar to QScriptEngine::ScriptOwnership. |
Generally an application doesn't need to set an object's ownership explicitly. The JavaScript memory manager uses a heuristic to set the default ownership. By default, an object that is created by the JavaScript memory manager has JavaScriptOwnership. The exception to this are the root objects created by calling QQmlComponent::create () 或 QQmlComponent::beginCreate (), which have CppOwnership by default. The ownership of these root-level objects is considered to have been transferred to the C++ caller.
Objects not-created by the JavaScript memory manager have CppOwnership by default. The exception to this are objects returned from C++ method calls; their ownership will be set to JavaScriptOwnership. This applies only to explicit invocations of Q_INVOKABLE methods or slots, but not to property getter invocations.
调用 setObjectOwnership () overrides the default ownership.
另请参阅 数据所有权 .
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.
访问函数:
QString | uiLanguage () const |
void | setUiLanguage (const QString & 语言 ) |
通知程序信号:
void | uiLanguageChanged () |
Constructs a QJSEngine object.
The globalObject () is initialized to have properties as described in ECMA-262 , Section 15.1.
[explicit]
QJSEngine::
QJSEngine
(
QObject
*
parent
)
Constructs a QJSEngine object with the given parent .
The globalObject () is initialized to have properties as described in ECMA-262 , Section 15.1.
[override virtual]
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 .
[since Qt 6.1]
QJSValue
QJSEngine::
catchError
()
If an exception is currently pending, catches it and returns it as a
QJSValue
. Otherwise returns undefined as
QJSValue
. After calling this method
hasError
() 返回
false
.
该函数在 Qt 6.1 引入。
返回给定
from
被转换成模板类型
To
. The conversion is done in JavaScript semantics. Those differ from
qvariant_cast
's semantics. There are a number of implicit conversions between JavaScript-equivalent types that are not performed by
qvariant_cast
by default. This method is a generalization of all the other conversion methods in this class.
另请参阅 fromVariant (), qvariant_cast (), fromScriptValue (),和 toScriptValue ().
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.
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.
exceptionStackTrace is used to report whether an uncaught exception was thrown. If you pass a non-null pointer to a QStringList to it, it will set it to list of "stackframe messages" if the script threw an unhandled exception, or an empty list otherwise. A stackframe message has the format function name:line number:column:file name
注意: In some cases, e.g. for native functions, function name and file name can be empty and line number and column can be -1.
注意:
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. Use
exceptionStackTrace->isEmpty()
to distinguish whether the value was a normal or an exceptional return value.
返回给定
value
被转换成模板类型
T
.
另请参阅 toManagedValue () 和 coerceValue ().
返回给定
value
被转换成模板类型
T
.
由于
QJSPrimitiveValue
can only hold int, bool, double,
QString
, and the equivalents of JavaScript
null
and
undefined
, the value will be coerced aggressively if you request any other type.
另请参阅 toPrimitiveValue () 和 coerceValue ().
返回给定
value
被转换成模板类型
T
.
另请参阅 toScriptValue () 和 coerceValue ().
返回给定
value
被转换成模板类型
T
. The conversion is done in JavaScript semantics. Those differ from
qvariant_cast
's semantics. There are a number of implicit conversions between JavaScript-equivalent types that are not performed by
qvariant_cast
在默认情况下。
另请参阅 coerceValue (), fromScriptValue (),和 qvariant_cast ().
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.
[since Qt 6.1]
bool
QJSEngine::
hasError
() const
返回
true
if the last JavaScript execution resulted in an exception or if
throwError
() was called. Otherwise returns
false
. Mind that
evaluate
() catches any exceptions thrown in the evaluated code.
该函数在 Qt 6.1 引入。
Imports the module located at fileName and returns a module namespace object that contains all exported variables, constants and functions as properties.
If this is the first time the module is imported in the engine, the file is loaded from the specified location in either the local file system or the Qt resource system and evaluated as an ECMAScript module. The file is expected to be encoded in UTF-8 text.
Subsequent imports of the same module will return the previously imported instance. Modules are singletons and remain around until the engine is destroyed.
指定 fileName will internally be normalized using QFileInfo::canonicalFilePath (). That means that multiple imports of the same file on disk using different relative paths will load the file only once.
注意:
If an exception is thrown during the loading of the module, the return value will be the exception (typically an
Error
object; see
QJSValue::isError
()).
另请参阅 registerModule ().
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);
另请参阅 Extension .
Returns whether JavaScript execution is currently interrupted.
另请参阅 setInterrupted ().
Creates a JavaScript object of class Array with the given length .
另请参阅 newObject ().
Creates a JavaScript object of class Error, with message as the error message.
The prototype of the created object will be errorType .
另请参阅 newObject (), throwError (),和 QJSValue::isError ().
Creates a JavaScript object of class Object.
The prototype of the created object will be the Object prototype object.
另请参阅 newArray () 和 QJSValue::setProperty ().
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.
另请参阅 newQObject () 和 QObject 集成 .
Creates a JavaScript object that wraps the static
QMetaObject
associated with class
T
.
另请参阅 newQObject () 和 QObject 集成 .
Creates a JavaScript object that wraps the given QObject object ,使用 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 ().
[since 6.2]
QJSValue
QJSEngine::
newSymbol
(const
QString
&
name
)
Creates a JavaScript object of class Symbol, with value name .
The prototype of the created object will be the Symbol prototype object.
该函数在 Qt 6.2 引入。
另请参阅 newObject ().
[static]
QJSEngine::ObjectOwnership
QJSEngine::
objectOwnership
(
QObject
*
object
)
Returns the ownership of object .
另请参阅 setObjectOwnership () 和 QJSEngine::ObjectOwnership .
注册 QJSValue to serve as a module. After this function is called, all modules that import moduleName will import the value of value instead of loading moduleName from the filesystem.
Any valid
QJSValue
can be registered, but named exports (i.e.
import { name } from "info"
are treated as members of an object, so the default export must be created with one of the newXYZ methods of
QJSEngine
.
Because this allows modules that do not exist on the filesystem to be imported, scripting applications can use this to provide built-in modules, similar to Node.js.
返回
true
当成功时,
false
否则。
注意: The QJSValue value is not called or read until it is used by another module. This means that there is no code to evaluate, so no errors will be seen until another module throws an exception while trying to load this module.
警告: Attempting to access a named export from a QJSValue that is not an object will trigger a exception .
另请参阅 importModule ().
Interrupts or re-enables JavaScript execution.
若
interrupted
is
true
, any JavaScript executed by this engine immediately aborts and returns an error object until this function is called again with a value of
false
for
interrupted
.
This function is thread safe. You may call it from a different thread in order to interrupt, for example, an infinite loop in JavaScript.
另请参阅 isInterrupted ().
[static]
void
QJSEngine::
setObjectOwnership
(
QObject
*
object
,
QJSEngine::ObjectOwnership
ownership
)
设置 ownership of object .
An object with
JavaScriptOwnership
is not garbage collected as long as it still has a parent, even if there are no references to it.
另请参阅 objectOwnership () 和 QJSEngine::ObjectOwnership .
[since Qt 5.12]
void
QJSEngine::
throwError
(const
QString
&
message
)
Throws a run-time error (exception) with the given message .
This method is the C++ counterpart of a
throw()
expression in JavaScript. It enables C++ code to report run-time errors to
QJSEngine
. Therefore it should only be called from C++ code that was invoked by a JavaScript function through
QJSEngine
.
When returning from C++, the engine will interrupt the normal flow of execution and call the next pre-registered exception handler with an error object that contains the given
message
. The error object will point to the location of the top-most context on the JavaScript caller stack; specifically, it will have properties
lineNumber
,
fileName
and
stack
. These properties are described in
脚本异常
.
In the following example a C++ method in
FileAccess.cpp
throws an error in
qmlFile.qml
at the position where
readFileAsText()
is called:
// qmlFile.qml function someFunction() { ... var text = FileAccess.readFileAsText("/path/to/file.txt"); }
// FileAccess.cpp // Assuming that FileAccess is a QObject-derived class that has been // registered as a singleton type and provides an invokable method // readFileAsText() QJSValue FileAccess::readFileAsText(const QString & filePath) { QFile file(filePath); if (!file.open(QIODevice::ReadOnly)) { jsEngine->throwError(file.errorString()); return QString(); } ... return content; }
It is also possible to catch the thrown error in JavaScript:
// qmlFile.qml function someFunction() { ... var text; try { text = FileAccess.readFileAsText("/path/to/file.txt"); } catch (error) { console.warn("In " + error.fileName + ":" + "error.lineNumber" + ": " + error.message); } }
If you need a more specific run-time error to describe an exception, you can use the throwError (QJSValue::ErrorType errorType, const QString &message) overload.
该函数在 Qt 5.12 引入。
另请参阅 脚本异常 .
[since Qt 5.12]
void
QJSEngine::
throwError
(
QJSValue::ErrorType
errorType
, const
QString
&
message
= QString())
This function overloads throwError().
Throws a run-time error (exception) with the given errorType and message .
// Assuming that DataEntry is a QObject-derived class that has been // registered as a singleton type and provides an invokable method // setAge(). void DataEntry::setAge(int age) { if (age < 0 || age > 200) { jsEngine->throwError(QJSValue::RangeError, "Age must be between 0 and 200"); } ... }
该函数在 Qt 5.12 引入。
另请参阅 脚本异常 and newErrorObject ().
[since 6.1]
void
QJSEngine::
throwError
(const
QJSValue
&
error
)
This function overloads throwError().
Throws a pre-constructed run-time error (exception). This way you can use newErrorObject () to create the error and customize it as necessary.
该函数在 Qt 6.1 引入。
另请参阅 脚本异常 and newErrorObject ().
创建 QJSManagedValue 采用给定 value .
另请参阅 fromManagedValue () 和 coerceValue ().
创建 QJSPrimitiveValue 采用给定 value .
由于
QJSPrimitiveValue
can only hold int, bool, double,
QString
, and the equivalents of JavaScript
null
and
undefined
, the value will be coerced aggressively if you pass any other type.
另请参阅 fromPrimitiveValue () 和 coerceValue ().
创建 QJSValue 采用给定 value .
另请参阅 fromScriptValue () 和 coerceValue ().
返回 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 ().