The JavaScript 主机环境 provided by QML can run valid standard JavaScript constructs such as conditional operators, arrays, variable setting, and loops. In addition to the standard JavaScript properties, the QML 全局对象 includes a number of helper methods that simplify building UIs and interacting with the QML environment.
The JavaScript environment provided by QML is stricter than that in a web browser. For example, in QML you cannot add to, or modify, members of the JavaScript global object. In regular JavaScript, it is possible to do this accidentally by using a variable without declaring it. In QML this will throw an exception, so all local variables must be explicitly declared. See JavaScript 环境限定 for a complete description of the restrictions on JavaScript code executed from QML.
Various parts of QML 文档 can contain JavaScript code:
在以下范例中,
color
property of
Rectangle
depends on the
pressed
property of
TapHandler
. This relationship is described using a conditional expression:
import QtQuick 2.12 Rectangle { id: colorbutton width: 200; height: 80; color: inputHandler.pressed ? "steelblue" : "lightsteelblue" TapHandler { id: inputHandler } }
In fact, any JavaScript expression (no matter how complex) may be used in a property binding definition, as long as the result of the expression is a value whose type can be assigned to the property. This includes side effects. However, complex bindings and side effects are discouraged because they can reduce the performance, readability, and maintainability of the code.
There are two ways to define a property binding: the most common one is shown in the example earlier, in a property initialization . The second (and much rarer) way is to assign the property a function returned from the Qt.binding () function, from within imperative JavaScript code, as shown below:
import QtQuick 2.12 Rectangle { id: colorbutton width: 200; height: 80; color: "red" TapHandler { id: inputHandler } Component.onCompleted: { color = Qt.binding(function() { return inputHandler.pressed ? "steelblue" : "lightsteelblue" }); } }
见 特性绑定 documentation for more information about how to define property bindings, and see the documentation about Property Assignment versus Property Binding for information about how bindings differ from value assignments.
QML object types can emit signals in reaction to certain events occurring. Those signals can be handled by signal handler functions, which can be defined by clients to implement custom program logic.
Suppose that a button represented by a Rectangle type has a
TapHandler
and a Text label. The
TapHandler
emits its
tapped
signal when the user presses the button. The clients can react to the signal in the
onTapped
handler using JavaScript expressions. The QML engine executes these JavaScript expressions defined in the handler as required. Typically, a signal handler is bound to JavaScript expressions to initiate other events or to assign property values.
import QtQuick 2.12 Rectangle { id: button width: 200; height: 80; color: "lightsteelblue" TapHandler { id: inputHandler onTapped: { // arbitrary JavaScript expression console.log("Tapped!") } } Text { id: label anchors.centerIn: parent text: inputHandler.pressed ? "Pressed!" : "Press here!" } }
For more details about signals and signal handlers, refer to the following topics:
Program logic can also be defined in JavaScript functions. These functions can be defined inline in QML documents (as custom methods) or externally in imported JavaScript files.
Custom methods can be defined in QML documents and may be called from signal handlers, property bindings, or functions in other QML objects. Such methods are often referred to as inline JavaScript functions because their implementation is included in the QML object type definition (QML document), instead of in an external JavaScript file.
An example of an inline custom method is as follows:
import QtQuick 2.12 Item { function fibonacci(n){ var arr = [0, 1]; for (var i = 2; i < n + 1; i++) arr.push(arr[i - 2] + arr[i -1]); return arr; } TapHandler { onTapped: console.log(fibonacci(10)) } }
The fibonacci function is run whenever the
TapHandler
发射
tapped
信号。
注意: The custom methods defined inline in a QML document are exposed to other objects, and therefore inline functions on the root object in a QML component can be invoked by callers outside the component. If this is not desired, the method can be added to a non-root object or, preferably, written in an external JavaScript file.
见 QML 对象属性 documentation for more information on defining custom methods in QML using JavaScript.
Non-trivial program logic is best separated into a separate JavaScript file. This file can be imported into QML using an
import
statement, like the QML
模块
.
例如,
fibonacci()
method in the earlier example could be moved into an external file named
fib.js
, and accessed like this:
import QtQuick 2.12 import "fib.js" as MathFunctions Item { TapHandler { onTapped: console.log(MathFunctions.fibonacci(10)) } }
For more information about loading external JavaScript files into QML, read the section about 在 QML 导入 JavaScript 资源 .
QML object types that emit signals also provide default signal handlers for their signals, as described in the previous section. Sometimes, however, a client wants to trigger a function defined in a QML object when another QML object emits a signal. Such scenarios can be handled by a signal connection.
A signal emitted by a QML object may be connected to a JavaScript function by calling the signal's
connect()
method and passing the JavaScript function as an argument. For example, the following code connects the
TapHandler
's
tapped
信号到
jsFunction()
in
script.js
:
import QtQuick 2.12 import "script.js" as MyScript Item { id: item width: 200; height: 200 TapHandler { id: inputHandler } Component.onCompleted: { inputHandler.tapped.connect(MyScript.jsFunction) } } |
// script.js function jsFunction() { console.log("Called JavaScript function!") } |
The
jsFunction()
被调用每当
TapHandler
's
tapped
信号被发射。
见 连接信号到方法和信号 了解更多信息。
It is occasionally necessary to run some imperative code at application (or component instance) startup. While it is tempting to just include the startup script as global code in an external script file, this can have severe limitations as the QML environment may not have been fully established. For example, some objects might not have been created or some 特性绑定 may not have been established. See JavaScript 环境限定 for the exact limitations of global script code.
A QML object emits the
Component.completed
attached signal
when its instantiation is complete. The JavaScript code in the corresponding
Component.onCompleted
handler runs after the object is instantiated. Thus, the best place to write application startup code is in the
Component.onCompleted
handler of the top-level object, because this object emits
Component.completed
when the QML environment is fully established.
例如:
import QtQuick 2.0 Rectangle { function startupFunction() { // ... startup code } Component.onCompleted: startupFunction(); }
Any object in a QML file - including nested objects and nested QML component instances - can use this attached property. If there is more than one
onCompleted()
handler to execute at startup, they are run sequentially in an undefined order.
Likewise, every
组件
发射
destruction
() signal just before being destroyed.