Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
expressions.qdoc
Go to the documentation of this file.
1// Copyright (C) 2017 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
3/*!
4\page qtqml-javascript-expressions.html
5\meta {keywords} {qmltopic}
6\title JavaScript Expressions in QML Documents
7\brief Description of where JavaScript expressions are valid in QML documents
8
9
10The \l{JavaScript Host Environment} provided by QML can run valid standard
11JavaScript constructs such as conditional operators, arrays, variable setting,
12and loops. In addition to the standard JavaScript properties, the \l {QML Global
13Object} includes a number of helper methods that simplify building UIs and
14interacting with the QML environment.
15
16The JavaScript environment provided by QML is stricter than that in a web
17browser. For example, in QML you cannot add to, or modify, members of the
18JavaScript global object. In regular JavaScript, it is possible to do this
19accidentally by using a variable without declaring it. In QML this will throw
20an exception, so all local variables must be explicitly declared. See
21\l{JavaScript Environment Restrictions} for a complete description of the
22restrictions on JavaScript code executed from QML.
23
24Various parts of \l{QML Documents}{QML documents} can contain JavaScript code:
25
26\list 1
27 \li The body of \l{Property Binding}{property bindings}. These JavaScript
28 expressions describe relationships between QML object \l{Property Attributes}
29 {properties}. When \e dependencies of a property change, the property
30 is automatically updated too, according to the specified relationship.
31 \li The body of \l{Signal Attributes}{Signal handlers}. These JavaScript
32 statements are automatically evaluated whenever a QML object emits the
33 associated signal.
34 \li The definition of \l{Method Attributes}{custom methods}. JavaScript functions
35 that are defined within the body of a QML object become methods of that
36 object.
37 \li Standalone \l{Importing JavaScript Resources in QML}{JavaScript resource
38 (.js) files}. These files are actually separate from QML documents, but
39 they can be imported into QML documents. Functions and variables that are
40 defined within the imported files can be used in property bindings, signal
41 handlers, and custom methods.
42\endlist
43
44
45
46\section1 JavaScript in property bindings
47
48In the following example, the \c color property of \l Rectangle depends on the
49\c pressed property of \l TapHandler. This relationship is described using a
50conditional expression:
51
52\qml
53import QtQuick 2.12
54
55Rectangle {
56 id: colorbutton
57 width: 200; height: 80;
58
59 color: inputHandler.pressed ? "steelblue" : "lightsteelblue"
60
61 TapHandler {
62 id: inputHandler
63 }
64}
65\endqml
66
67In fact, any JavaScript expression (no matter how complex) may be used in a
68property binding definition, as long as the result of the expression is a
69value whose type can be assigned to the property. This includes side effects.
70However, complex bindings and side effects are discouraged because they can
71reduce the performance, readability, and maintainability of the code.
72
73There are two ways to define a property binding: the most common one
74is shown in the example earlier, in a \l{QML Object Attributes#Value Assignment on Initialization}
75{property initialization}. The second (and much rarer) way is to assign the
76property a function returned from the \l{Qt::binding()}{Qt.binding()} function,
77from within imperative JavaScript code, as shown below:
78
79\qml
80import QtQuick 2.12
81
82Rectangle {
83 id: colorbutton
84 width: 200; height: 80;
85
86 color: "red"
87
88 TapHandler {
89 id: inputHandler
90 }
91
92 Component.onCompleted: {
93 color = Qt.binding(function() { return inputHandler.pressed ? "steelblue" : "lightsteelblue" });
94 }
95}
96\endqml
97
98See the \l{Property Binding}{property bindings} documentation for more
99information about how to define property bindings, and see the documentation
100about \l{qml-javascript-assignment}
101{Property Assignment versus Property Binding} for information about how
102bindings differ from value assignments.
103
104\section1 JavaScript in signal handlers
105
106QML object types can emit signals in reaction to certain events occurring.
107Those signals can be handled by signal handler functions, which can be defined
108by clients to implement custom program logic.
109
110Suppose that a button represented by a Rectangle type has a TapHandler and a
111Text label. The TapHandler emits its \l{TapHandler::}{tapped} signal when the
112user presses the button. The clients can react to the signal in the \c onTapped
113handler using JavaScript expressions. The QML engine executes these JavaScript
114expressions defined in the handler as required. Typically, a signal handler is
115bound to JavaScript expressions to initiate other events or to assign property
116values.
117
118\qml
119import QtQuick 2.12
120
121Rectangle {
122 id: button
123 width: 200; height: 80; color: "lightsteelblue"
124
125 TapHandler {
126 id: inputHandler
127 onTapped: {
128 // arbitrary JavaScript expression
129 console.log("Tapped!")
130 }
131 }
132
133 Text {
134 id: label
135 anchors.centerIn: parent
136 text: inputHandler.pressed ? "Pressed!" : "Press here!"
137 }
138}
139\endqml
140
141For more details about signals and signal handlers, refer to the following
142topics:
143
144\list
145 \li \l{Signal and Handler Event System}
146 \li \l{QML Object Attributes}
147\endlist
148
149\section1 JavaScript in standalone functions
150
151Program logic can also be defined in JavaScript functions. These functions can
152be defined inline in QML documents (as custom methods) or externally in
153imported JavaScript files.
154
155\section2 JavaScript in custom methods
156
157Custom methods can be defined in QML documents and may be called from signal
158handlers, property bindings, or functions in other QML objects. Such methods
159are often referred to as \e{inline JavaScript functions} because their
160implementation is included in the QML object type definition
161(QML document), instead of in an external JavaScript file.
162
163An example of an inline custom method is as follows:
164
165\qml
166import QtQuick 2.12
167
168Item {
169 function fibonacci(n){
170 var arr = [0, 1];
171 for (var i = 2; i < n + 1; i++)
172 arr.push(arr[i - 2] + arr[i -1]);
173
174 return arr;
175 }
176 TapHandler {
177 onTapped: console.log(fibonacci(10))
178 }
179}
180\endqml
181
182The fibonacci function is run whenever the TapHandler emits a \c tapped signal.
183
184\note The custom methods defined inline in a QML document are exposed to
185other objects, and therefore inline functions on the root object in a QML
186component can be invoked by callers outside the component. If this is not
187desired, the method can be added to a non-root object or, preferably, written
188in an external JavaScript file.
189
190See the \l{QML Object Attributes} documentation for more information on
191defining custom methods in QML using JavaScript.
192
193\section2 Functions defined in a JavaScript file
194
195Non-trivial program logic is best separated into a separate JavaScript file.
196This file can be imported into QML using an \c import statement, like the
197QML \l {QML Modules}{modules}.
198
199For example, the \c {fibonacci()} method in the earlier example could be moved
200into an external file named \c fib.js, and accessed like this:
201
202\qml
203import QtQuick 2.12
204import "fib.js" as MathFunctions
205
206Item {
207 TapHandler {
208 onTapped: console.log(MathFunctions.fibonacci(10))
209 }
210}
211\endqml
212
213For more information about loading external JavaScript files into QML, read
214the section about \l{Importing JavaScript Resources in QML}.
215
216\section2 Connecting signals to JavaScript functions
217
218QML object types that emit signals also provide default signal handlers for
219their signals, as described in the \l{JavaScript in signal handlers}{previous}
220section. Sometimes, however, a client wants to trigger a function defined in a
221QML object when another QML object emits a signal. Such scenarios can be handled
222by a signal connection.
223
224A signal emitted by a QML object may be connected to a JavaScript function
225by calling the signal's \c connect() method and passing the JavaScript function
226as an argument. For example, the following code connects the TapHandler's
227\c tapped signal to the \c jsFunction() in \c script.js:
228
229\table
230\row
231\li \snippet qml/integrating-javascript/connectjs.qml 0
232\li \snippet qml/integrating-javascript/script.js 0
233\endtable
234
235The \c jsFunction() is called whenever the TapHandler's \c tapped signal
236is emitted.
237
238See \l{qtqml-syntax-signals.html}
239{Connecting Signals to Methods and Signals} for more information.
240
241\section1 JavaScript in application startup code
242
243It is occasionally necessary to run some imperative code at application (or
244component instance) startup. While it is tempting to just include the startup
245script as \e {global code} in an external script file, this can have severe
246limitations as the QML environment may not have been fully established. For
247example, some objects might not have been created or some
248\l {Property Binding}{property bindings} may not have been established. See
249\l {JavaScript Environment Restrictions} for the exact limitations of global
250script code.
251
252A QML object emits the \c{Component.completed} \l{Signal and Handler Event
253System#Attached Signal Handlers}{attached signal} when its instantiation is
254complete. The JavaScript code in the corresponding \c{Component.onCompleted}
255handler runs after the object is instantiated. Thus, the best place to write
256application startup code is in the \c{Component.onCompleted} handler of the
257top-level object, because this object emits \c{Component.completed} when the
258QML environment is fully established.
259
260For example:
261
262\qml
263import QtQuick 2.0
264
265Rectangle {
266 function startupFunction() {
267 // ... startup code
268 }
269
270 Component.onCompleted: startupFunction();
271}
272\endqml
273
274Any object in a QML file - including nested objects and nested QML component
275instances - can use this attached property. If there is more than one
276\c onCompleted() handler to execute at startup, they are run sequentially in
277an undefined order.
278
279Likewise, every \c Component emits a \l {Component::destruction}{destruction()}
280signal just before being destroyed.
281
282*/
283
284/*
285 \internal
286 NOTE: TODO Qt 5.1: We are not sufficiently confident about the implementation of scarce
287 resources in Qt 5.0.0, so mark this section as internal for now.
288 It should eventually become public API
289
290 There is another section about scarce resources in valuetypes.qdoc. It should
291 be enabled at the same time.
292
293
294
295\section1 Scarce Resources in JavaScript
296
297As described in the documentation for \l{QML Value Types}, a \c var type
298property may hold a \e{scarce resource} (image or pixmap). There are several
299important semantics of scarce resources which should be noted:
300
301\list
302\li By default, a scarce resource is automatically released by the declarative engine as soon as evaluation of the expression in which the scarce resource is allocated is complete if there are no other references to the resource
303\li A client may explicitly preserve a scarce resource, which will ensure that the resource will not be released until all references to the resource are released and the JavaScript engine runs its garbage collector
304\li A client may explicitly destroy a scarce resource, which will immediately release the resource
305\endlist
306
307In most cases, allowing the engine to automatically release the resource is
308the correct choice. In some cases, however, this may result in an invalid
309variant being returned from a function in JavaScript, and in those cases it
310may be necessary for clients to manually preserve or destroy resources for
311themselves.
312
313For the following examples, imagine that we have defined the following class:
314
315\snippet qml/integrating-javascript/scarceresources/avatarExample.h 0
316
317and that we have registered it with the QML type-system as follows:
318
319\snippet qml/integrating-javascript/scarceresources/scarceresources.pro 0
320
321The AvatarExample class has a property which is a pixmap. When the property
322is accessed in JavaScript scope, a copy of the resource will be created and
323stored in a JavaScript object which can then be used within JavaScript. This
324copy will take up valuable system resources, and so by default the scarce
325resource copy in the JavaScript object will be released automatically by the
326declarative engine once evaluation of the JavaScript expression is complete,
327unless the client explicitly preserves it.
328
329\section2 Example One: Automatic Release
330
331In the following example, the scarce resource will be automatically released
332after the binding evaluation is complete. Assume we have the following qml file:
333
334\snippet qml/integrating-javascript/scarceresources/exampleOne.qml 0
335
336And then use it from C++:
337
338\snippet qml/integrating-javascript/scarceresources/avatarExample.cpp 1
339
340\section2 Example Two: Automatic Release Prevented By Reference
341
342In this example, the resource will not be automatically
343released after the binding expression evaluation is
344complete, because there is a property var referencing the
345scarce resource.
346
347\snippet qml/integrating-javascript/scarceresources/exampleTwo.qml 0
348
349And from C++:
350
351\snippet qml/integrating-javascript/scarceresources/avatarExample.cpp 2
352
353\section2 Example Three: Explicit Preservation
354
355In this example, the resource must be explicitly preserved in order
356to prevent the declarative engine from automatically releasing the
357resource after evaluation of the imported script.
358
359We create a JavaScript file:
360\snippet qml/integrating-javascript/scarceresources/exampleThree.js 0
361
362Import it in QML:
363\snippet qml/integrating-javascript/scarceresources/exampleThree.qml 0
364
365Run it in C++:
366\snippet qml/integrating-javascript/scarceresources/avatarExample.cpp 3
367
368\section2 Example Four: Explicit Destruction
369
370In the following example, we release (via destroy()) an explicitly preserved
371scarce resource variant. This example shows how a client may free system
372resources by releasing the scarce resource held in a JavaScript object, if
373required, during evaluation of a JavaScript expression.
374
375We create a JavaScript file:
376\snippet qml/integrating-javascript/scarceresources/exampleFour.js 0
377
378Import it in QML:
379\snippet qml/integrating-javascript/scarceresources/exampleFour.qml 0
380
381Run it in C++:
382\snippet qml/integrating-javascript/scarceresources/avatarExample.cpp 4
383
384\section2 Example Five: Explicit Destruction and JavaScript References
385
386One thing to be aware of when using "var" type properties is that they
387hold references to JavaScript objects. As such, if multiple references
388to one scarce resource is held, and the client calls destroy() on one
389of those references (to explicitly release the scarce resource), all of
390the references will be affected.
391
392
393\snippet qml/integrating-javascript/scarceresources/exampleFive.qml 0
394
395Run it in C++:
396\snippet qml/integrating-javascript/scarceresources/avatarExample.cpp 5
397
398*/