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
structure.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-documents-structure.html
5\title Structure of a QML Document
6\brief Description of the structure of QML documents
7
8
9A QML document is a self contained piece of QML source code that consists of three parts:
10
11 \list
12 \li An optional list of pragmas
13 \li Its \e import statements
14 \li A single root object declaration
15 \endlist
16
17By convention, a single empty line separates the imports from the object hierarchy definition.
18
19QML documents are always encoded in UTF-8 format.
20
21
22
23\keyword QML.pragma
24\section1 Pragmas
25
26Pragmas are instructions to the QML engine itself that can be used to specify
27certain characteristics of objects in the current file or to modify how the
28engine interprets code. The following pragmas are exaplained in details below.
29
30\table
31\header
32 \li pragma
33 \li values
34 \li default value
35 \li since
36\row
37 \li \l{Structure of a QML Document#Singleton}{Singleton}
38 \li
39 \li
40 \li 5.2 //! 200a869441562d62e7fc0867599097e0599f0411
41\row
42 \li {1, 3} \l{Structure of a QML Document#ListPropertyAssignBehavior}{ListPropertyAssignBehavior}
43 \li Append
44 \li X
45 \li 6.3 //! f2a15482ddd289a36b04316a2b6ebed83eb017c5
46\row
47 \li Replace
48 \li
49 \li 6.3
50\row
51 \li ReplaceIfNotDefault
52 \li
53 \li 6.3
54\row
55 \li {1, 2} \l{Structure of a QML Document#ComponentBehavior}{ComponentBehavior}
56 \li Bound
57 \li
58 \li 6.4 //! 4d71091a198fbbd3f84c61af0f2915493f2dad1a
59\row
60 \li Unbound
61 \li X
62 \li 6.4 //! 4d71091a198fbbd3f84c61af0f2915493f2dad1a
63\row
64 \li {1, 2} \l{Structure of a QML Document#FunctionSignatureBehavior}{FunctionSignatureBehavior}
65 \li Ignored
66 \li
67 \li 6.5 //! de2d7cba76bcfbe0a29271df1178c176d00bf9b4
68\row
69 \li Enforced
70 \li X
71 \li 6.5
72\row
73 \li {1, 2} \l{Structure of a QML Document#NativeMethodBehavior}{NativeMethodBehavior}
74 \li AcceptThisObject
75 \li
76 \li 6.5 //! 3fd3a2a9d06505d549cc4a7c18819a17c6622dfd
77\row
78 \li RejectThisObject
79 \li X
80 \li 6.5
81\row
82 \li {1, 5} \l{Structure of a QML Document#ValueTypeBehavior}{ValueTypeBehavior}
83 \li Reference
84 \li X
85 \li 6.5 //! ec58c0ddb7fe1ebf33c80335ab9435e53fd00274
86\row
87 \li Copy
88 \li
89 \li 6.5
90\row
91 \li Addressable
92 \li
93 \li 6.6 //! 35152b432e82fc274c3983d0f369666a899cde49
94\row
95 \li Inaddressable
96 \li X
97 \li 6.6
98\row
99 \li Assertable
100 \li
101 \li 6.8 //! 71e259837967f1eee50c057229094c2a971a1a61
102\row
103 \li \l{Structure of a QML Document#Translator}{Translator}
104 \li <translation context>
105 \li <file name>
106 \li 6.7 //! d6e0d5630a49e9614a70bf960a213b3eff03a68e
107\endtable
108
109\keyword QML.Singleton
110\section2 Singleton
111
112\c{pragma Singleton} declares the component defined at the root of the QML
113document as singleton. See \l {Singletons in QML} for more information.
114
115\keyword QML.ListPropertyAssignBehavior
116\keyword QML.Append
117\keyword QML.ReplaceIfNotDefault
118\section2 ListPropertyAssignBehavior
119
120With this pragma you can define how assignments to list properties shall be
121handled in components defined in the QML document. By default, assigning to a
122list property appends to the list. You can explicitly request this behavior
123using the value \c{Append}. Alternatively, you can request the contents of list
124properties to always be replaced using \c{Replace}, or replaced if the property
125is not the default property using \c{ReplaceIfNotDefault}.
126
127Consider a base type in a document Base.qml:
128\qml
129pragma ListPropertyAssignBehavior: ReplaceIfNotDefault
130import QtQuick
131
132Item {
133 objectName: "outer"
134
135 default property list<Item> d: [
136 Item { objectName: "inner" }
137 ]
138
139 property list<Item> notDefault: [
140 Item { objectName: "one" }
141 ]
142}
143\endqml
144
145Then, if you derive from Base and modify its list properties, the
146ListPropertyAssignBehavior takes effect. In this case:
147
148\qml
149Base {
150 // The new item is appended to the list even though you're assigning.
151 // The (default) property "d" now contains "inner" and "inner2".
152 d: [
153 Item { objectName: "inner2" }
154 ]
155
156 // The list is replaced by the list given here.
157 // The (non-default) property "notDefault" now contains only "two".
158 notDefault: [
159 Item { objectName: "two" }
160 ]
161}
162\endqml
163
164If no \c{ListPropertyAssignBehavior} is given or if \c{Append} is given, the
165"two" object will be appended to the \c{notDefault} property instead, resulting
166in a list that contains both, "one" and "two".
167
168If \c{Replace} is given, the contents of the default property "d" will also be
169replaced, resulting in a list that contains only "inner2".
170
171\note The same declaration can also be given for C++-defined types, by adding
172the \l{QML_LIST_PROPERTY_ASSIGN_BEHAVIOR_APPEND},
173\l{QML_LIST_PROPERTY_ASSIGN_BEHAVIOR_REPLACE}, and
174\l{QML_LIST_PROPERTY_ASSIGN_BEHAVIOR_REPLACE_IF_NOT_DEFAULT} macros to the
175class declaration. For example:
176
177\code
178class MyType : public QObject
179{
180 Q_OBJECT
181 QML_ELEMENT
182 QML_LIST_PROPERTY_ASSIGN_BEHAVIOR_REPLACE
183
184 Q_PROPERTY(QQmlListProperty<QObject> a READ a)
185 [...]
186};
187\endcode
188
189\keyword QML.ComponentBehavior
190\keyword QML.Bound
191\keyword QML.Unbound
192\section2 ComponentBehavior
193
194You may have multiple components defined in the same QML file. The root
195scope of the QML file is a component, and you may additionally have
196elements of type \l QQmlComponent, explicitly or implicitly created
197as properties, or inline components. Those components are nested. Each
198of the inner components is within one specific outer component. Most of
199the time, IDs defined in an outer component are accessible within all
200its nested inner components. You can, however, create elements from a
201component in any a different context, with different IDs available.
202Doing so breaks the assumption that outer IDs are available. Therefore,
203the engine and the QML tooling cannot generally know in advance what
204type, if any, such IDs will resolve to at run time.
205
206With the ComponentBehavior pragma you can restrict all inner components
207defined in a file to only create objects within their original context.
208If a component is bound to its context, you can safely use IDs from
209outer components in the same file within the component. QML tooling will
210then assume the outer IDs with their specific types to be available.
211
212In order to bind the components to their context specify the \c{Bound}
213argument:
214
215\qml
216pragma ComponentBehavior: Bound
217\endqml
218
219This implies that, in case of name clashes, IDs defined outside a bound
220component override local properties of objects created from the
221component. Otherwise it wouldn't actually be safe to use the IDs since
222later versions of a module might add more properties to the component.
223If the component is not bound, local properties override IDs defined
224outside the component, but not IDs defined inside the component.
225
226The example below prints the \e r property of the ListView object with
227the id \e color, not the \e r property of the rectangle's color.
228
229\qml
230pragma ComponentBehavior: Bound
231import QtQuick
232
233ListView {
234 id: color
235 property int r: 12
236 model: 1
237
238 delegate: Rectangle {
239 Component.onCompleted: console.log(color.r)
240 }
241}
242\endqml
243
244The default value of \c ComponentBehavior is \c{Unbound}. You can also
245specify it explicitly. In a future version of Qt the default will change
246to \c{Bound}.
247
248Delegate components bound to their context don't receive their own
249private contexts on instantiation. This means that model data can only
250be passed via \l{Required Properties}{required properties} in this case.
251Passing model data via context properties will not work. This concerns
252delegates to e.g. \l{Instantiator}, \l{Repeater}, \l{ListView},
253\l{TableView}, \l{GridView}, \l{TreeView} and in general anything that
254uses \l{DelegateModel} internally.
255
256For example, the following will \e{not} work:
257
258\qml
259pragma ComponentBehavior: Bound
260import QtQuick
261
262ListView {
263 delegate: Rectangle {
264 color: model.myColor
265 }
266}
267\endqml
268
269The \c{delegate} property of \l{ListView} is a component. Therefore, a
270\l{Component} is implicitly created around the \l{Rectangle} here. That
271component is bound to its context. It doesn't receive the context property
272\c{model} provided by \l{ListView}. To make it work, you'd have to write
273it this way:
274
275\qml
276pragma ComponentBehavior: Bound
277import QtQuick
278
279ListView {
280 delegate: Rectangle {
281 required property color myColor
282 color: myColor
283 }
284}
285\endqml
286
287You can nest components in a QML file. The pragma holds for all components in
288the file, no matter how deeply nested.
289
290\keyword QML.FunctionSignatureBehavior
291\keyword QML.Ignored
292\keyword QML.Enforced
293\section2 FunctionSignatureBehavior
294
295With this pragma you can change the way type annotations on functions
296are handled. Since Qt 6.7 type annotations are enforced when calling
297functions. Before, only the \l{QML script compiler} enforced the type
298annotations. The interpreter and JIT compiler ignored them. Always
299enforcing the type annotations is a behavior change in comparison to
300earlier versions since you could call functions with mismatched
301arguments before.
302
303Specifying \c{Ignored} as value makes the QML engine and the
304\l{QML script compiler} ignore any type annotations and therefore
305restores the pre-6.7 behavior of the interpreter and JIT. As a result
306less code is compiled to C++ ahead of time, and more code has to be
307interpreted or JIT-compiled.
308
309Specifying \c{Enforced} as value explicitly states the default: Type
310annotations are always enforced.
311
312\sa {Type annotations and assertions}
313
314\keyword QML.NativeMethodBehavior
315\keyword QML.AcceptThisObject
316\keyword QML.RejectThisObject
317\section2 NativeMethodBehavior
318
319Calling C++ methods with \c this objects different from the one they were
320retrieved from is broken, due to historical reasons. The original object is
321used as \c this object. You can allow the given \c this object to be used by
322setting \c {pragma NativeMethodBehavior: AcceptThisObject}. Specifying
323\c RejectThisObject keeps the historical behavior.
324
325An example of this can be found under \l {C++ methods and the 'this' object}.
326
327\keyword QML.ValueTypeBehavior
328\keyword QML.Addressable
329\keyword QML.Inaddressable
330\keyword QML.Assertable
331\keyword QML.Copy
332\keyword QML.Reference
333\section2 ValueTypeBehavior
334
335With this pragma you can change the way value types and sequences are handled.
336
337Usually lower case names cannot be type names in JavaScript code. This is a
338problem because value type names are lower case. You can specify \c{Addressable}
339as value for this pragma to change this. If \c{Addressable} is specified a
340JavaScript value can be explicitly coerced to a specific, named, value type. This is
341done using the \c as operator, like you would do with object types. Furthermore,
342you can also check for value types using the \c instanceof operator:
343
344\qml
345pragma ValueTypeBehavior: Addressable
346import QtQml
347
348QtObject {
349 property var a
350 property real b: (a as rect).x
351 property bool c: a instanceof rect
352
353 property var rect // inaccessible. "rect" is a type name.
354}
355\endqml
356
357Since \c rect in the above example is now a type name, it will shadow any
358properties called \c{rect}.
359
360Explicitly casting to the desired type helps tooling. It can allow the
361\l{Qt Quick Compiler} generate efficient code where it otherwise would not be
362able to. You can use \l{qmllint} to find such occurrences.
363
364There is also a \c{Inaddressable} value you can use to explicitly specify the
365default behavior.
366
367Another attribute to the \c{ValueTypeBehavior} pragma is \c{Assertable},
368introduced in Qt 6.8. Due to a mistake in Qt 6.6 and 6.7 the \c{a as rect} above
369not only checks whether \c{a} is a \c{rect} but also constructs a \c{rect} if
370\c{a} is of a compatible type. This is obviously not what a type assertion
371should do. Specifying \c{Assertable} prevents this behavior and restricts type
372assertions for value types to only check for the type. You should always specify
373it if you are going to use value types with \c{as}. In any case, if the
374type assertion for a value type fails, the result is \c{undefined}.
375
376\c{instanceof} does not have this problem since it only checks for inheritance,
377not for all possible type coercions.
378
379\note Using \c{as} with the \c{int} and \c{double} types is not advisable since by
380JavaScript rules, the result of any calculation is a floating point number, even
381if it happens to hold the same value as its integer equivalent. Conversely, any
382integer constant you declare in JavaScript is not a double by QML's type mapping
383rules. Furthermore, \c{int} and \c{double} are reserved words. You can only
384address these types via type namespaces.
385
386Value types and sequences are generally treated as references. This means, if
387you retrieve a value type instance from a property into a local value, and then
388change the local value, the original property is also changed. Furthermore,
389if you write the original property explicitly, the local value is also updated.
390This behavior is rather unintuitive in many places, and you should not rely on
391it. The \c{Copy} and \c{Reference} values for the \c{ValueTypeBehavior} pragma
392are experimental options to change this behavior. You should not use them.
393Specifying \c{Copy} causes all value types to be treated as actual copies.
394Specifying \c{Reference} explicitly states the default behavior.
395
396Rather than using \c{Copy} you should explicitly re-load references to value
397types and sequences any time they can have been affected by side effects. Side
398effects can happen whenever you call a function or imperatively set a property.
399\l{qmllint} provides guidance on this. For example, in the following code
400the variable \c f is affected by side effects after writing \c width. This is
401because there may be a binding in a derived type or in a \c Binding element
402that updates \c font when \c width is changed.
403
404\qml
405import QtQuick
406Text {
407 function a() : real {
408 var f = font;
409 width = f.pixelSize;
410 return f.pointSize;
411 }
412}
413\endqml
414
415In order to address this, you can avoid holding \c f across the write operation
416on \c width:
417
418\qml
419import QtQuick
420Text {
421 function a() : real {
422 var f = font;
423 width = f.pixelSize;
424 f = font;
425 return f.pointSize;
426 }
427}
428\endqml
429
430This, in turn can be shortened to:
431
432\qml
433import QtQuick
434Text {
435 function a() : real {
436 width = font.pixelSize;
437 return font.pointSize;
438 }
439}
440\endqml
441
442You might assume that re-retrieving the \c font property is costly, but actually
443the QML engine automatically refreshes value type references each time you read
444from them. So this is not more expensive than the first version, but a clearer
445way to express the same operations.
446
447\sa {Type annotations and assertions}
448
449\keyword QML.Translator
450\section2 Translator
451
452With this pragma you can set the context for the translations in the file.
453
454\qml
455pragma Translator: myTranslationContext
456\endqml
457
458\qml
459pragma Translator: "myTranslationContext"
460\endqml
461
462For more information on internationalization with QML, see
463\l{Writing Source Code for Translation#QML}{Writing Source Code for Translation in QML}.
464
465\section1 Imports
466
467A document must import the necessary modules or type namespaces to enable the
468engine to load the QML object types referenced within the document. By default,
469a document can access any QML object types that have been defined through
470\c .qml files in the same directory; if a document needs to refer to any other
471object types, it must import the type namespace into which those types have
472been registered.
473
474QML does \e not have a preprocessor that modifies the document prior to
475presentation to the \l{QQmlEngine}{QML engine}, unlike C or C++.
476The \c import statements do not copy and prepend the code in the document, but
477instead instruct the QML engine on how to resolve type references found
478in the document. Any type reference present in a QML document - such as \c
479Rectangle and \c ListView - including those made within a \l {JavaScript
480Expressions in QML Documents}{JavaScript block} or \l {Property Binding}{property
481bindings}, are \e resolved based exclusively on the import statements. At least
482one \c import statement must be present such as \c{import QtQuick 2.0}.
483
484Please see the \l{qtqml-syntax-imports.html}{QML Syntax - Import Statements}
485documentation for in-depth information about QML imports.
486
487
488\section1 The Root Object Declaration
489
490A QML document describes a hierarchy of objects which can be instantiated.
491Each object definition has a certain structure; it has a type, it can have an
492id and an object name, it can have properties, it can have methods, it can have
493signals and it can have signal handlers.
494
495A QML file must only contain \b {a single root object definition}. The following
496is invalid and will generate an error:
497
498\badcode
499// MyQmlFile.qml
500import QtQuick 2.0
501
502Rectangle { width: 200; height: 200; color: "red" }
503Rectangle { width: 200; height: 200; color: "blue" } // invalid!
504\endcode
505
506This is because a .qml file automatically defines a QML type, which encapsulates a \e single QML object definition. This is discussed further in \l{qtqml-documents-definetypes.html}{Documents as QML object type definitions}.
507
508*/