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