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