继承者: QQmlApplicationEngine , QQmlEngine
def
collectGarbage
()
def
evaluate
(program[, fileName=””[, lineNumber=1]])
def
globalObject
()
def
importModule
(fileName)
def
installExtensions
(extensions[, object=QJSValue()])
def
installTranslatorFunctions
([object=QJSValue()])
def
isInterrupted
()
def
newArray
([length=0])
def
newErrorObject
(errorType[, message=””])
def
newObject
()
def
newQMetaObject
(metaObject)
def
newQObject
(object)
def
setInterrupted
(interrupted)
def
setUiLanguage
(language)
def
throwError
(errorType[, message=””])
def
throwError
(message)
def
toScriptValue
(arg__1)
def
uiLanguage
()
def
uiLanguageChanged
()
使用
evaluate()to evaluate script code.QJSEngine myEngine; QJSValue three = myEngine.evaluate("1 + 2");
evaluate()返回QJSValuethat holds the result of the evaluation. TheQJSValueclass provides functions for converting the result to various C++ types (e.g.toString()andtoNumber()).The following code snippet shows how a script function can be defined and then invoked from C++ using
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 theErrorobject 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 oneevaluate()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; }
globalObject()函数返回 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()ornewObject()函数。
evaluate()can throw a script exception (e.g. due to a syntax error). If it does, thenevaluate()returns the value that was thrown (typically anErrorobject). UseisError()to check for exceptions.For detailed information about the error, use
toString()to obtain an error message, and useproperty()to query the properties of theErrorobject. The following properties are available:
name
message
fileName
lineNumber
stackQJSValue 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 statementnew Object(). You can use the object-specific functionality inQJSValueto manipulate the script object (e.g.setProperty()). Similarly, usenewArray()to create a JavaScript array object.
使用
newQObject()to wrap aQObject(or subclass) pointer.newQObject()returns a proxy script object; properties, children, and signals and slots of theQObjectare 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 aQMetaObject; this gives you a “script representation” of aQObject-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 newQObjectinstance with JavaScriptOwnership. For example, given the following class definition:class MyObject : public QObject { Q_OBJECT public: Q_INVOKABLE MyObject() {} };
staticMetaObjectfor 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_OBJECTmacro are supported; it is not possible to expose thestaticMetaObjectof aQ_GADGETclass to JavaScript.
Dynamic
QObjectproperties 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();
QJSEngineprovides a compliant ECMAScript implementation. By default, familiar utilities like logging are not available, but they can can be installed via theinstallExtensions()函数。另请参阅
QJSValueMaking Applications Scriptable List of JavaScript Objects and Functions
QJSEngine
¶
QJSEngine(parent)
- param parent
QObject
构造
QJSEngine
对象。
globalObject()
is initialized to have properties as described in
ECMA-262
, Section 15.1.
构造
QJSEngine
对象采用给定
parent
.
globalObject()
is initialized to have properties as described in
ECMA-262
, Section 15.1.
PySide2.QtQml.QJSEngine.
Extension
¶
This enum is used to specify extensions to be installed via
installExtensions()
.
|
常量 |
描述 |
|---|---|
|
QJSEngine.TranslationExtension |
Indicates that translation functions (
|
|
QJSEngine.ConsoleExtension |
Indicates that console functions (
|
|
QJSEngine.GarbageCollectionExtension |
Indicates that garbage collection functions (
|
|
QJSEngine.AllExtensions |
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() |
|
|
|
|
|
qsTranslate() |
|
|
|
|
|
qsTrId() |
|
|
|
|
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
控制台 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
gc()
function is equivalent to calling
collectGarbage()
.
New in version 5.6.
PySide2.QtQml.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.
PySide2.QtQml.QJSEngine.
evaluate
(
program
[
,
fileName=""
[
,
lineNumber=1
]
]
)
¶
program – unicode
fileName – unicode
lineNumber
–
int
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
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.,
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.
PySide2.QtQml.QJSEngine.
globalObject
(
)
¶
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.
PySide2.QtQml.QJSEngine.
importModule
(
fileName
)
¶
fileName – unicode
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
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
isError()
).
PySide2.QtQml.QJSEngine.
installExtensions
(
extensions
[
,
object=QJSValue()
]
)
¶
extensions
–
扩展
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);
另请参阅
Extension
PySide2.QtQml.QJSEngine.
installTranslatorFunctions
(
[
object=QJSValue()
]
)
¶
object
–
QJSValue
注意
此函数被弃用。
Installs translator functions on the given
object
, or on the Global Object if no object is specified.
The relation between script translator functions and C++ translator functions is described in the following table:
|
Script Function |
Corresponding C++ Function |
|
qsTr() |
|
|
|
|
|
qsTranslate() |
|
|
|
|
|
qsTrId() |
|
|
|
|
It also adds an arg() method to the string prototype.
另请参阅
国际化
with
Qt
PySide2.QtQml.QJSEngine.
isInterrupted
(
)
¶
bool
Returns whether JavaScript execution is currently interrupted.
另请参阅
PySide2.QtQml.QJSEngine.
newArray
(
[
length=0
]
)
¶
length
–
uint
Creates a JavaScript object of class Array with the given
length
.
另请参阅
PySide2.QtQml.QJSEngine.
newErrorObject
(
errorType
[
,
message=""
]
)
¶
errorType
–
ErrorType
message – unicode
Creates a JavaScript object of class Error, with
message
as the error message.
The prototype of the created object will be
errorType
.
PySide2.QtQml.QJSEngine.
newObject
(
)
¶
Creates a JavaScript object of class Object.
The prototype of the created object will be the Object prototype object.
另请参阅
PySide2.QtQml.QJSEngine.
newQMetaObject
(
metaObject
)
¶
metaObject
–
QMetaObject
Creates a JavaScript object that wraps the given
QMetaObject
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
Integration
PySide2.QtQml.QJSEngine.
newQObject
(
object
)
¶
object
–
QObject
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
.
另请参阅
PySide2.QtQml.QJSEngine.
setInterrupted
(
interrupted
)
¶
interrupted
–
bool
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.
另请参阅
PySide2.QtQml.QJSEngine.
setUiLanguage
(
language
)
¶
language – unicode
另请参阅
PySide2.QtQml.QJSEngine.
throwError
(
errorType
[
,
message=""
]
)
¶
errorType
–
ErrorType
message – unicode
此函数重载
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");
}
...
}
另请参阅
Script
异常
newErrorObject()
PySide2.QtQml.QJSEngine.
throwError
(
message
)
¶
message – unicode
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 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
Script
异常
.
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
ErrorType
errorType,
const
QString
&message)
overload.
另请参阅
Script
异常
PySide2.QtQml.QJSEngine.
uiLanguage
(
)
¶
unicode
另请参阅
PySide2.QtQml.QJSEngine.
uiLanguageChanged
(
)
¶