Qt 6.x
The Qt SDK
Loading...
Searching...
No Matches
hostenvironment.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-hostenvironment.html
5\title JavaScript Host Environment
6\brief Description of the JavaScript host environment provided by the QML engine
7
8
9QML provides a JavaScript host environment tailored to writing QML applications.
10This environment is different from the host environment provided by a browser
11or a server-side JavaScript environment such as Node.js. For example, QML does
12not provide a \c window object or \c{DOM API} as commonly found in a browser environment.
13
14\section1 Common Base
15
16Like a browser or server-side JavaScript environment, the QML runtime implements the
17\l{ECMA-262}{ECMAScript Language Specification} standard. This provides access to
18all of the built-in types and functions defined by the standard, such as Object, Array, and Math.
19The QML runtime implements the 7th edition of the standard.
20
21\l{Nullish Coalescing} (\c{??}) (since Qt 5.15) and \l{Optional Chaining} (\c{?.}) (since Qt 6.2)
22are also implemented in the QML runtime.
23
24The standard ECMAScript built-ins are not explicitly documented in the QML documentation. For more
25information on their use, please refer to the ECMA-262 7th edition standard or one of the many online
26JavaScript reference and tutorial sites, such as the \l{W3Schools JavaScript Reference} (JavaScript Objects
27Reference section). Many sites focus on JavaScript in the browser, so in some cases you may need to double
28check the specification to determine whether a given function or object is part of standard ECMAScript or
29specific to the browser environment. In the case of the W3Schools link above, the \c{JavaScript Objects
30Reference} section generally covers the standard, while the \c{Browser Objects Reference} and \c{HTML DOM
31Objects Reference} sections are browser specific (and thus not applicable to QML).
32
33\section1 Type annotations and assertions
34
35Function declarations in QML documents can, and should, contain type
36annotations. Type annotations are appended to the declaration of arguments and
37to the function itself, for annotating the return type. The following function
38takes an \c int and a \c string parameter, and returns a \c QtObject:
39
40\qml
41function doThings(a: int, b: string) : QtObject { ... }
42\endqml
43
44Type annotations help tools like \l{Qt Creator} and \l{qmllint} to make sense
45of the code and provide better diagnostics. Moreover, they make functions easier
46to use from C++. See
47\l {qtqml-cppintegration-interactqmlfromcpp.html}{Interacting with QML Objects from C++}
48for more information.
49
50By default, type annotations are ignored by the interpreter and the JIT
51compiler, but enforced by \l{qmlcachegen} and \l{qmlsc} when compiling to C++.
52This can lead to differences in behavior if you either pass values that
53are not actually of the declared type or if you modify instances of
54\l{QML Value Types} passed as typed arguments. Value types are passed by
55reference by the interpreter and JIT, but by value when compiled to C++.
56
57You can eliminate those differences by either forcing the interpreter and JIT
58to also respect type annotations or by having \l{qmlcachegen} and \l{qmlsc}
59ignore type annotations. The former has a performance cost when using the
60interpreter or JIT, the latter makes the compilation to C++ avoid any JavaScript
61functions, and any bindings and signal handlers that call JavaScript functions.
62Therefore less code will be compiled to C++.
63
64In order to always enforce type annotations, add the following to your QML
65document:
66\qml
67pragma FunctionSignatureBehavior: Enforced
68\endqml
69
70In order to always ignore type annotations, add the following instead:
71\qml
72pragma FunctionSignatureBehavior: Ignored
73\endqml
74
75Type assertions (sometimes called \e as-casts) can also be used in order to cast an object to a
76different object type. If the object is actually of the given type, then the type assertion returns
77the same object. If not, it returns \c null. In the following snippet we assert that the \c parent
78object is a \c Rectangle before accessing a specific member of it.
79
80\qml
81Item {
82 property color parentColor: (parent as Rectangle)?.color || "red"
83}
84\endqml
85
86The optional chaining (\c{?.}) avoids throwing an exception if the parent is
87actually not a rectangle. In that case "red" is chosen as \c parentColor.
88
89\section1 QML Global Object
90
91The QML JavaScript host environment implements a number of host objects and functions, as
92detailed in the \l{QML Global Object} documentation.
93
94These host objects and functions are always available, regardless of whether any modules
95have been imported.
96
97
98\section1 JavaScript Objects and Functions
99
100A list of the JavaScript objects, functions and properties supported by the
101QML engine can be found in the \l{List of JavaScript Objects and Functions}.
102
103Note that QML makes the following modifications to native objects:
104
105\list
106\li An \l {string}{arg()} function is added to the \c String prototype.
107\li Locale-aware conversion functions are added to the \l Date and \l Number prototypes.
108\endlist
109
110In addition, QML also extends the behavior of the instanceof function to
111allow for type checking against QML types. This means that you may use it to
112verify that a variable is indeed the type you expect, for example:
113
114\qml
115 var v = something();
116 if (!v instanceof Item) {
117 throw new TypeError("I need an Item type!");
118 }
119
120 ...
121\endqml
122
123
124\section1 JavaScript Environment Restrictions
125
126QML implements the following restrictions for JavaScript code:
127
128\list
129\li JavaScript code written in a \c .qml file cannot modify the global object.
130 JavaScript code in a .js file can modify the global object,
131 and those modifications will be visible to the .qml file when
132 \l {Importing a JavaScript Resource from a QML Document}{imported}.
133
134In QML, the global object is constant - existing properties cannot be modified
135or deleted, and no new properties may be created.
136
137Most JavaScript programs do not intentionally modify the global object.
138However, JavaScript's automatic creation of undeclared variables is an implicit
139modification of the global object, and is prohibited in QML.
140
141Assuming that the \c a variable does not exist in the scope chain, the
142following code is illegal in QML:
143
144\code
145// Illegal modification of undeclared variable
146a = 1;
147for (var ii = 1; ii < 10; ++ii)
148 a = a * ii;
149console.log("Result: " + a);
150\endcode
151
152It can be trivially modified to this legal code.
153
154\code
155var a = 1;
156for (var ii = 1; ii < 10; ++ii)
157 a = a * ii;
158console.log("Result: " + a);
159\endcode
160
161Any attempt to modify the global object - either implicitly or explicitly - will
162cause an exception. If uncaught, this will result in a warning being printed,
163that includes the file and line number of the offending code.
164
165\li Global code is run in a reduced scope.
166
167During startup, if a QML file includes an external JavaScript file with "global"
168code, it is executed in a scope that contains only the external file itself and
169the global object. That is, it will not have access to the QML objects and
170properties it \l {Scope and Naming Resolution}{normally would}.
171
172Global code that only accesses script local variables is permitted. This is an
173example of valid global code.
174
175\code
176var colors = [ "red", "blue", "green", "orange", "purple" ];
177\endcode
178
179Global code that accesses QML objects will not run correctly.
180
181\code
182// Invalid global code - the "rootObject" variable is undefined
183var initialPosition = { rootObject.x, rootObject.y }
184\endcode
185
186This restriction exists as the QML environment is not yet fully established.
187To run code after the environment setup has completed, see
188\l {JavaScript in Application Startup Code}.
189
190\li The value of \c this is undefined in QML in the majority of contexts.
191
192The \c this keyword is supported when binding properties from JavaScript.
193In QML binding expressions, QML signal handlers, and QML declared functions,
194\c this refers to the scope object. In all other situations, the value of
195\c this is undefined in QML.
196
197To refer to a specific object, provide an \c id. For example:
198
199\qml
200Item {
201 width: 200; height: 100
202 function mouseAreaClicked(area) {
203 console.log("Clicked in area at: " + area.x + ", " + area.y);
204 }
205 // This will pass area to the function
206 MouseArea {
207 id: area
208 y: 50; height: 50; width: 200
209 onClicked: mouseAreaClicked(area)
210 }
211}
212\endqml
213
214\sa {Scope and Naming Resolution}
215
216\endlist
217
218
219
220*/