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
valuetypes.qdoc
Go to the documentation of this file.
1// Copyright (C) 2022 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
3/*!
4\page qtqml-typesystem-valuetypes.html
5\meta {keywords} {qmltopic}
6\title QML Value Types
7\brief Description of QML value types.
8
9QML supports built-in and custom value types.
10
11A \e{value type} is one that is conceptually passed by value rather than by
12reference, such as an \c int or a \c string. This contrasts with
13\l{qtqml-typesystem-topic.html#qml-object-types}{QML Object Types}. Object types
14are passed by reference. If you assign an instance of an object type to two
15different properties, both properties carry the same value. Modifying the object
16is reflected in both properties. If you assign an instance of a value type to
17two different properties, the properties carry separate values. If you modify
18one of them, the other one stays the same. Value types are only conceptually
19passed by value since it must still be possible to interact with them as if they
20were JavaScript objects. To facilitate this, in reality they are passed as
21\l{QML Value Type and Sequence References}{Value Type References} when you access
22them from JavaScript code.
23
24Unlike an object type, a value type cannot be used to declare QML objects:
25it is not possible, for example, to declare an \c int{} object or a \c size{} object.
26
27Value types can be used to refer to:
28
29\list
30\li A single value (e.g. \l int refers to a single number)
31\li A value that contains properties and methods (e.g. \l size refers to a value with \c width and \c height properties)
32\li The generic type \l{var}. It can hold values of any other type but is itself a value type.
33\endlist
34
35When a variable or property holds a value type and it is assigned to another
36variable or property, then a copy of the value is made.
37
38\sa {qtqml-typesystem-topic.html}{The QML Type System}
39
40
41\section1 Available Value Types
42
43Some value types are supported by the engine by default and do not require an
44\l {Import Statements}{import statement} to be used, while others do require
45the client to import the module which provides them.
46All of the value types listed below may be used as a \c property type in a QML
47document, with the following exceptions:
48\list
49 \li \c void, which marks the absence of a value
50 \li \c list must be used in conjunction with an object or value type as element
51\endlist
52
53\section2 Built-in Value Types Provided By The QML Language
54
55The built-in value types supported natively in the \l{The QML Reference}{QML language} are listed below:
56\annotatedlist qmlvaluetypes
57
58\section2 Value Types Provided By QML Modules
59
60QML modules may extend the QML language with more value types.
61
62For instance, the value types provided by the \c QtQml module are:
63\annotatedlist qtqmlvaluetypes
64
65The value types provided by the \c QtQuick module are:
66\annotatedlist qtquickvaluetypes
67
68The \l{QtQml::Qt}{Qt} global object provides \l{globalqtobjecttypes}{useful functions} for manipulating values of value
69types for the \l{Qt Qml} and \l{Qt Quick} modules.
70
71Other Qt modules will document their value types on their respective module pages.
72
73You may define your own value types as described in
74\l{qtqml-cppintegration-definetypes.html}{Defining QML Types from C++}.
75In order to use types provided by a particular QML module, clients
76must import that module in their QML documents.
77
78\section1 Property Change Behavior for Value Types
79
80Some value types have properties: for example, the \l font type has
81\c pixelSize, \c family and \c bold properties. Unlike properties of
82\l{qtqml-typesystem-topic.html#qml-object-types}{object types}, properties of
83value types do not provide their own property change signals. It is only possible
84to create a property change signal handler for the value type property itself:
85
86\code
87Text {
88 // invalid!
89 onFont.pixelSizeChanged: doSomething()
90
91 // also invalid!
92 font {
93 onPixelSizeChanged: doSomething()
94 }
95
96 // but this is ok
97 onFontChanged: doSomething()
98}
99\endcode
100
101Be aware, however, that a property change signal for a value type is emitted
102whenever \e any of its attributes have changed, as well as when the property itself
103changes. Take the following code, for example:
104
105\qml
106Text {
107 onFontChanged: console.log("font changed")
108
109 Text { id: otherText }
110
111 focus: true
112
113 // changing any of the font attributes, or reassigning the property
114 // to a different font value, will invoke the onFontChanged handler
115 Keys.onDigit1Pressed: font.pixelSize += 1
116 Keys.onDigit2Pressed: font.b = !font.b
117 Keys.onDigit3Pressed: font = otherText.font
118}
119\endqml
120
121In contrast, properties of an \l{qtqml-typesystem-topic.html#qml-object-types}{object type}
122emit their own property change signals, and a property change signal handler for an object-type
123property is only invoked when the property is reassigned to a different object value.
124
125*/
126
127/*!
128 \qmlvaluetype int
129 \ingroup qmlvaluetypes
130 \brief a whole number, e.g. 0, 10, or -20.
131
132 The \c int type refers to a whole number, e.g. 0, 10, or -20.
133
134 The possible \c int values range from -2147483648 to 2147483647,
135 although most types will only accept a reduced range (which they
136 mention in their documentation).
137
138 Example:
139 \qml
140 NumberAnimation { loops: 5 }
141 \endqml
142
143 This value type is provided by the QML language.
144
145 \sa {QML Value Types}
146*/
147
148/*!
149 \qmlvaluetype bool
150 \ingroup qmlvaluetypes
151 \brief a binary true/false value.
152
153 The \c bool type refers to a binary true/false value.
154
155 Properties of type \c bool have \c false as their default value.
156
157 Example:
158 \qml
159 Item {
160 focus: true
161 clip: false
162 }
163 \endqml
164
165 This value type is provided by the QML language.
166
167 \sa {QML Value Types}
168*/
169
170/*!
171 \qmlvaluetype real
172 \ingroup qmlvaluetypes
173
174 \brief a number with a decimal point.
175
176 The \c real type refers to a number with decimal point, e.g. 1.2 or -29.8.
177
178 Example:
179 \qml
180 Item { width: 100.45; height: 150.82 }
181 \endqml
182
183 \note In QML all reals are stored in double precision, \l
184 {http://en.wikipedia.org/wiki/IEEE_754} {IEEE floating point}
185 format.
186
187 This value type is provided by the QML language.
188
189 \sa {QML Value Types}
190*/
191
192/*!
193 \qmlvaluetype double
194 \ingroup qmlvaluetypes
195
196 \brief a number with a decimal point, stored in double precision.
197
198 The \c double type refers to a number with a decimal point and is stored in double precision, \l
199 {http://en.wikipedia.org/wiki/IEEE_754} {IEEE floating point} format. It's the same as \c real.
200
201 Properties of type \c double have \e {0.0} as their default value.
202
203 Example:
204 \qml
205 Item {
206 property double number: 32155.2355
207 }
208 \endqml
209
210 This value type is provided by the QML language.
211
212 \sa {QML Value Types}
213*/
214
215/*!
216 \qmlvaluetype string
217 \ingroup qmlvaluetypes
218 \brief A free form text string.
219
220 The \c string type refers to a free form text string in quotes, for example
221 "Hello world!". The QML language provides this value type by default.
222
223 Example:
224 \qml
225 Text { text: "Hello world!" }
226 \endqml
227
228 Properties of type \c string are empty by default.
229
230 Strings have a \c length attribute that holds the number of characters in
231 the string.
232
233 The string value type is backed by the C++ type QString. It extends the
234 JavaScript String primitive type in that it provides much of the same API,
235 plus some extra methods. For example, the QML string value type method
236 \c {arg()} supports value substitution:
237
238 \qml
239 var message = "There are %1 items"
240 var count = 20
241 console.log(message.arg(count)) // "There are 20 items"
242 \endqml
243
244 \since 6.12
245 The \c {arg()} method also supports multiple arguments, allowing you to
246 replace multiple placeholders in a single call:
247
248 \qml
249 var message = "%1 of %2 files copied. Errors: %3"
250 console.log(message.arg(5, 7, 0)) // "5 of 7 files copied. Errors: 0"
251 \endqml
252
253 Using multiple arguments is more efficient than chaining \c {arg()} calls
254 and protects against issues when arguments themselves contain placeholders:
255
256 \qml
257 var result = "%1 %2".arg("%1f", "Hello") // "%1f Hello" (correct)
258 // Compare with chained calls:
259 var result = "%1 %2".arg("%1f").arg("Hello") // "Hellof %2" (incorrect)
260 \endqml
261
262 The QML string value type supports most of the ECMAScript string features,
263 such as template (string) literals, string interpolation, multi-line
264 strings, and looping over strings.
265
266 In general, QML string supports most JavaScript String methods, including
267 checking for inclusion using \c string.includes(), \c string.startsWith(),
268 and \c string.endsWith(); repeating a string using \c string.repeats(), and
269 slicing and splitting using \c string.slice() and \c string.split().
270
271 For more information about which version of ECMAScript QML supports, see
272 \l {JavaScript Host Environment}
273
274 For more information about JavaScript String methods, see
275 \l {https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String}
276 {mdn JavaScript String}
277
278 When integrating with C++, note that any QString value
279 \l{qtqml-cppintegration-data.html}{passed into QML from C++} is
280 automatically converted into a \c string value, and vice-versa.
281
282 \sa {QML Value Types}, {ECMA-262}{ECMAScript Language Specification}
283*/
284
285/*!
286 \qmlvaluetype url
287 \ingroup qmlvaluetypes
288 \brief a resource locator.
289
290 The \c url type refers to a resource locator (like a file name, for example). It can be either
291 absolute, e.g. "http://qt-project.org", or relative, e.g. "pics/logo.png". A relative URL is
292 resolved relative to the URL of the containing component.
293
294 For example, the following assigns a valid URL to the \l {Image::source}
295 property, which is of type \c url:
296
297 \qml
298 Image { source: "pics/logo.png" }
299 \endqml
300
301 When integrating with C++, note that any QUrl value
302 \l{qtqml-cppintegration-data.html}{passed into QML from C++} is automatically
303 converted into a \c url value, and vice-versa.
304
305 Alternatively you may convert your \c url to a \l{https://developer.mozilla.org/en-US/docs/Web/API/URL}{URL} object
306 in order to access and modify its components:
307 \qml
308 var urlObject = new URL(url);
309 \endqml
310
311 \note In Qt 5, URLs were automatically resolved based on the current context
312 when assigning them to any \c url property. This made it impossible to
313 work with relative URLs and it created inconsistent behavior when reading
314 back a URL previously written to a property. Therefore, the behavior was
315 changed in Qt 6: URLs are not automatically resolved on assignment anymore.
316 The individual elements that use URLs have to resolve them themselves.
317
318 \note When referring to files stored with the \l{resources.html}{Qt Resource System}
319 from within QML, you should use "qrc:///" instead of ":/" as QML requires
320 URLs rather than paths. Relative URLs resolved from within that file will
321 use the same scheme.
322
323 \note Additionally, URLs may contain encoded characters using the
324 'percent-encoding' scheme specified by
325 \l {https://datatracker.ietf.org/doc/html/rfc3986}{RFC 3986}. These
326 characters will be preserved within properties of type \c url, to allow QML
327 code to construct precise URL values.
328
329 For example, a local file containing a '#' character, which would normally be
330 interpreted as the beginning of the URL 'fragment' element, can be accessed by
331 encoding the characters of the file name:
332
333 \qml
334 Image { source: "file:///tmp/" + encodeURIComponent("test#1.png") }
335 \endqml
336
337 However, this also holds for slashes, backslashes, and \c nul characters.
338 If you do \c{encodeURIComponent("/tmp/test#1.png")} you get
339 \c{%2Ftmp%2Ftest%231.png}. This is generally not what you want and in
340 particular it is \e not a local file \e path. The encoded slashes are now
341 part of the file \e name and resolving this URL in the context of, say,
342 \c{qrc:/qt/qml/MyModule/Main.qml} results in the following URL:
343 \c{qrc:/qt/qml/MyModule/%2Ftmp%2Ftest%231.png}.
344
345 If you need more control over the construction of URLs, you can use a JavaScript
346 \l{https://developer.mozilla.org/en-US/docs/Web/API/URL}{URL} object.
347
348 This value type is provided by the QML language.
349
350 \sa {QML Value Types}
351*/
352
353
354/*!
355 \qmlvaluetype list
356 \ingroup qmlvaluetypes
357 \brief a list of QML objects.
358
359 The \c list type refers to a list of QML objects or values.
360
361 Properties of type \c list are empty by default.
362
363 A \c list can store QML objects or \l{QML Value Types}{value type} values.
364
365 When integrating with C++, note that any QQmlListProperty value
366 \l{qtqml-cppintegration-data.html}{passed into QML from C++} is automatically
367 converted into a \c list value, and vice-versa.
368
369 Similarly any \c{QList<T>} of a registered value type \c{T} is automatically
370 converted into a \c list value, and vice-versa.
371
372 \section1 Using the list Type
373
374 For example, the \l Item type has a \l {Item::}{states} list-type property that
375 can be assigned to and used as follows:
376
377 \qml
378 import QtQuick
379
380 Item {
381 width: 100; height: 100
382
383 states: [
384 State { name: "activated" },
385 State { name: "deactivated" }
386 ]
387
388 Component.onCompleted: {
389 console.log("Name of first state:", states[0].name)
390 for (var i = 0; i < states.length; i++)
391 console.log("state", i, states[i].name)
392 }
393 }
394 \endqml
395
396 The defined \l State objects will be added to the \c states list
397 in the order in which they are defined.
398
399 If the list only contains one object, the square brackets may be omitted:
400
401 \qml
402 import QtQuick
403
404 Item {
405 width: 100; height: 100
406 states: State { name: "activated" }
407 }
408 \endqml
409
410 You can also declare your own list properties in QML:
411
412 \qml
413 import QtQml
414
415 QtObject {
416 property list<int> intList: [1, 2, 3, 4]
417 property list<QtObject> objectList
418 }
419 \endqml
420
421 Lists can be used much like JavaScript arrays. For example:
422
423 \list
424 \li Values are assigned using the \c[] square bracket syntax with comma-separated values
425 \li The \c length property provides the number of items in the list
426 \li Values in the list are accessed using the \c [index] syntax
427 \li You can use \c{push()} to append entries
428 \li You can set the \c length property of the list to truncate or extend it.
429 \endlist
430
431 However, you can \e{not} automatically extend the list by assigning to an
432 index currently out of range. Furthermore, if you insert \c null values
433 into a list of objects, those are converted to \c nullptr entries in
434 the underlying QQmlListProperty.
435
436 A list of value types is different from a JavaScript array in one further
437 important aspect: Growing it by setting its length does not produce undefined
438 entries, but rather default-constructed instances of the value type.
439
440 Similarly, growing a list of object types this way produces null entries,
441 rather than undefined entries.
442
443 This value type is provided by the QML language.
444
445 \sa {QML Value Types}
446*/
447
448 /*!
449 \qmlvaluetype var
450 \ingroup qmlvaluetypes
451 \brief a generic property type.
452
453 The \c var type is a generic property type that can refer to any data type.
454
455 It is equivalent to a regular JavaScript variable.
456 For example, var properties can store numbers, strings, objects,
457 arrays and functions:
458
459 \qml
460 Item {
461 property var aNumber: 100
462 property var aBool: false
463 property var aString: "Hello world!"
464 property var anotherString: String("#FF008800")
465 property var aColor: Qt.rgba(0.2, 0.3, 0.4, 0.5)
466 property var aRect: Qt.rect(10, 10, 10, 10)
467 property var aPoint: Qt.point(10, 10)
468 property var aSize: Qt.size(10, 10)
469 property var aVector3d: Qt.vector3d(100, 100, 100)
470 property var anArray: [1, 2, 3, "four", "five", (function() { return "six"; })]
471 property var anObject: { "foo": 10, "bar": 20 }
472 property var aFunction: (function() { return "one"; })
473 }
474 \endqml
475
476 \section1 Change Notification Semantics
477
478 It is important to note that changes in regular properties of JavaScript
479 objects assigned to a var property will \b{not} trigger updates of bindings
480 that access them. The example below will display "The car has 4 wheels" as
481 the change to the wheels property will not cause the reevaluation of the
482 binding assigned to the "text" property:
483
484 \qml
485 Item {
486 property var car: new Object({wheels: 4})
487
488 Text {
489 text: "The car has " + car.wheels + " wheels";
490 }
491
492 Component.onCompleted: {
493 car.wheels = 6;
494 }
495 }
496 \endqml
497
498 If the onCompleted handler instead had \tt{"car = new Object({wheels: 6})"}
499 then the text would be updated to say "The car has 6 wheels", since the
500 car property itself would be changed, which causes a change notification
501 to be emitted.
502
503 \section1 Property Value Initialization Semantics
504
505 The QML syntax defines that curly braces on the right-hand-side of a
506 property value initialization assignment denote a binding assignment.
507 This can be confusing when initializing a \c var property, as empty curly
508 braces in JavaScript can denote either an expression block or an empty
509 object declaration. If you wish to initialize a \c var property to an
510 empty object value, you should wrap the curly braces in parentheses.
511
512 Properties of type \c var are \c {undefined} by default.
513
514 For example:
515 \qml
516 Item {
517 property var first: {} // nothing = undefined
518 property var second: {{}} // empty expression block = undefined
519 property var third: ({}) // empty object
520 }
521 \endqml
522
523 In the previous example, the \c first property is bound to an empty
524 expression, whose result is undefined. The \c second property is bound to
525 an expression which contains a single, empty expression block ("{}"), which
526 similarly has an undefined result. The \c third property is bound to an
527 expression which is evaluated as an empty object declaration, and thus the
528 property will be initialized with that empty object value.
529
530 Similarly, a colon in JavaScript can be either an object property value
531 assignment, or a code label. Thus, initializing a var property with an
532 object declaration can also require parentheses:
533
534 \qml
535 Item {
536 property var first: { example: 'true' } // example is interpreted as a label
537 property var second: ({ example: 'true' }) // example is interpreted as a property
538 property var third: { 'example': 'true' } // example is interpreted as a property
539 Component.onCompleted: {
540 console.log(first.example) // prints 'undefined', as "first" was assigned a string
541 console.log(second.example) // prints 'true'
542 console.log(third.example) // prints 'true'
543 }
544 }
545 \endqml
546
547 \sa {QML Value Types}
548*/
549
550/*!
551 \qmlvaluetype variant
552 \ingroup qmlvaluetypes
553 \brief a generic property type.
554
555 The \c variant type is the same as the \c var type. Use \c var instead.
556
557 \sa {QML Value Types}
558*/
559
560/*!
561 \qmlvaluetype void
562 \ingroup qmlvaluetypes
563 \brief The empty value type.
564
565 The \c void type is exclusively used to type-annotate JavaScript functions
566 returning \c undefined. For example:
567
568 \qml
569 function doThings() : void { console.log("hello") }
570 \endqml
571
572 This is to help tooling analyze calls to such functions and compile them and
573 their callers to C++.
574
575 You cannot declare \c void properties in QML.
576
577 \sa {QML Value Types}
578*/
579
580/*!
581 \qmlvaluetype regex
582 \ingroup qmlvaluetypes
583 \internal
584 \brief Represents regular expressions.
585
586 \sa {QML Value Types}
587*/