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
objectattributes.qdoc
Go to the documentation of this file.
1// Copyright (C) 2023 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
3
4/*!
5\page qtqml-syntax-objectattributes.html
6\title QML Object Attributes
7\brief Description of QML object type attributes
8
9Every QML object type has a defined set of attributes. Each instance of an
10object type is created with the set of attributes that have been defined for
11that object type. There are several different kinds of attributes which
12can be specified, which are described below.
13
14\section1 Attributes in Object Declarations
15
16An \l{qtqml-syntax-basics.html#object-declarations}{object declaration} in a
17QML document defines a new type. It also declares an object hierarchy that
18will be instantiated should an instance of that newly defined type be created.
19
20The set of QML object-type attribute types is as follows:
21
22\list
23\li the \e id attribute
24\li property attributes
25\li signal attributes
26\li signal handler attributes
27\li method attributes
28\li attached properties and attached signal handler attributes
29\li enumeration attributes
30\endlist
31
32These attributes are discussed in detail below.
33
34\section2 The \e id Attribute
35\keyword QML.id
36
37Every QML object type has exactly one \e id attribute. This attribute is
38provided by the language itself, and cannot be redefined or overridden by any
39QML object type.
40
41A value may be assigned to the \e id attribute of an object instance to allow
42that object to be identified and referred to by other objects. This \c id must
43begin with a lower-case letter or an underscore, and cannot contain characters
44other than letters, numbers and underscores.
45
46Below is a \l TextInput object and a \l Text object. The \l TextInput object's
47\c id value is set to "myTextInput". The \l Text object sets its \c text
48property to have the same value as the \c text property of the \l TextInput,
49by referring to \c myTextInput.text. Now, both items will display the same
50text:
51
52\qml
53import QtQuick
54
55Column {
56 width: 200; height: 200
57
58 TextInput { id: myTextInput; text: "Hello World" }
59
60 Text { text: myTextInput.text }
61}
62\endqml
63
64An object can be referred to by its \c id from anywhere within the
65\e {component scope} in which it is declared. Therefore, an \c id value must
66always be unique within its component scope. See
67\l{qtqml-documents-scope.html}{Scope and Naming Resolution} for more
68information.
69
70Once an object instance is created, the value of its \e id attribute cannot
71be changed. While it may look like an ordinary property, the \c id attribute
72is \b{not} an ordinary \c property attribute, and special semantics apply
73to it; for example, it is not possible to access \c myTextInput.id in the above
74example.
75
76
77\section2 Property Attributes
78
79A property is an attribute of an object that can be assigned a static value
80or bound to a dynamic expression. A property's value can be read by other
81objects. Generally it can also be modified by another object, unless a
82particular QML type has explicitly disallowed this for a specific property.
83
84\section3 Defining Property Attributes
85
86A property may be defined for a type in C++ by registering a
87Q_PROPERTY of a class which is then registered with the QML type system.
88Alternatively, a custom property of an object type may be defined in
89an object declaration in a QML document with the following syntax:
90
91\code
92 [default] [required] [readonly] property <propertyType> <propertyName>
93\endcode
94
95In this way an object declaration may \l {Defining Object Types from QML}
96{expose a particular value} to outside objects or maintain some internal
97state more easily.
98
99Property names must begin with a lower case letter and can only contain
100letters, numbers and underscores. \l {JavaScript Reserved Words}
101{JavaScript reserved words} are not valid property names. The \c default,
102\c required, and \c readonly keywords are optional, and modify the semantics
103of the property being declared.
104See the upcoming sections on \l {Default Properties}{default properties},
105\l {Required Properties}{required properties} and,
106\l {Read-Only Properties}{read-only properties} for more information
107about their respective meaning.
108
109Declaring a custom property implicitly creates a value-change
110\l{Signal attributes}{signal} for that property, as well as an associated
111\l{Signal handler attributes}{signal handler} called
112\e on<PropertyName>Changed, where \e <PropertyName> is the name of the
113property, with the first letter capitalized.
114
115For example, the following object declaration defines a new type which
116derives from the Rectangle base type. It has two new properties,
117with a \l{Signal handler attributes}{signal handler} implemented for one of
118those new properties:
119
120\qml
121Rectangle {
122 property color previousColor
123 property color nextColor
124 onNextColorChanged: console.log("The next color will be: " + nextColor.toString())
125}
126\endqml
127
128\section4 Valid Types in Custom Property Definitions
129
130Any of the \l {QML Value Types} aside from the \l enumeration type can be used
131as custom property types. For example, these are all valid property declarations:
132
133\qml
134Item {
135 property int someNumber
136 property string someString
137 property url someUrl
138}
139\endqml
140
141(Enumeration values are simply whole number values and can be referred to with
142the \l int type instead.)
143
144Some value types are provided by the \c QtQuick module and thus cannot be used
145as property types unless the module is imported. See the \l {QML Value Types}
146documentation for more details.
147
148Note the \l var value type is a generic placeholder type that can hold any
149type of value, including lists and objects:
150
151\code
152property var someNumber: 1.5
153property var someString: "abc"
154property var someBool: true
155property var someList: [1, 2, "three", "four"]
156property var someObject: Rectangle { width: 100; height: 100; color: "red" }
157\endcode
158
159Additionally, any \l{QML Object Types}{QML object type} can be used as a
160property type. For example:
161
162\code
163property Item someItem
164property Rectangle someRectangle
165\endcode
166
167This applies to \l {Defining Object Types from QML}{custom QML types} as well.
168If a QML type was defined in a file named \c ColorfulButton.qml (in a directory
169which was then imported by the client), then a property of type
170\c ColorfulButton would also be valid.
171
172
173\section3 Assigning Values to Property Attributes
174
175The value of a property of an object instance may be specified in two separate ways:
176\list
177 \li a value assignment on initialization
178 \li an imperative value assignment
179\endlist
180
181In either case, the value may be either a \e static value or a \e {binding expression}
182value.
183
184\section4 Value Assignment on Initialization
185
186The syntax for assigning a value to a property on initialization is:
187
188\code
189 <propertyName> : <value>
190\endcode
191
192An initialization value assignment may be combined with a property definition
193in an object declaration, if desired. In that case, the syntax of the property
194definition becomes:
195
196\code
197 [default] property <propertyType> <propertyName> : <value>
198\endcode
199
200An example of property value initialization follows:
201
202\qml
203import QtQuick
204
205Rectangle {
206 color: "red"
207 property color nextColor: "blue" // combined property declaration and initialization
208}
209\endqml
210
211\section4 Imperative Value Assignment
212
213An imperative value assignment is where a property value (either static value
214or binding expression) is assigned to a property from imperative JavaScript
215code. The syntax of an imperative value assignment is just the JavaScript
216assignment operator, as shown below:
217
218\code
219 [<objectId>.]<propertyName> = value
220\endcode
221
222An example of imperative value assignment follows:
223
224\qml
225import QtQuick
226
227Rectangle {
228 id: rect
229 Component.onCompleted: {
230 rect.color = "red"
231 }
232}
233\endqml
234
235\section3 Static Values and Binding Expression Values
236
237As previously noted, there are two kinds of values which may be assigned to a
238property: \e static values, and \e {binding expression} values. The latter are
239also known as \l{Property Binding}{property bindings}.
240
241\table
242 \header
243 \li Kind
244 \li Semantics
245
246 \row
247 \li Static Value
248 \li A constant value which does not depend on other properties.
249
250 \row
251 \li Binding Expression
252 \li A JavaScript expression which describes a property's relationship with
253 other properties. The variables in this expression are called the
254 property's \e dependencies.
255
256 The QML engine enforces the relationship between a property and its
257 dependencies. When any of the dependencies change in value, the QML
258 engine automatically re-evaluates the binding expression and assigns
259 the new result to the property.
260\endtable
261
262Here is an example that shows both kinds of values being assigned to properties:
263
264\qml
265import QtQuick
266
267Rectangle {
268 // both of these are static value assignments on initialization
269 width: 400
270 height: 200
271
272 Rectangle {
273 // both of these are binding expression value assignments on initialization
274 width: parent.width / 2
275 height: parent.height
276 }
277}
278\endqml
279
280\note To assign a binding expression imperatively, the binding expression
281must be contained in a function that is passed into \l{Qt::binding()}{Qt.binding()},
282and then the value returned by Qt.binding() must be assigned to the property.
283In contrast, Qt.binding() must not be used when assigning a binding expression
284upon initialization. See \l{Property Binding} for more information.
285
286
287\section3 Type Safety
288
289Properties are type safe. A property can only be assigned a value that matches
290the property type.
291
292For example, if a property is a real, and if you try to assign a string to it,
293you will get an error:
294
295\code
296property int volume: "four" // generates an error; the property's object will not be loaded
297\endcode
298
299Likewise if a property is assigned a value of the wrong type during run time,
300the new value will not be assigned, and an error will be generated.
301
302Some property types do not have a natural
303value representation, and for those property types the QML engine
304automatically performs string-to-typed-value conversion. So, for example,
305even though properties of the \c color type store colors and not strings,
306you are able to assign the string \c "red" to a color property, without an
307error being reported.
308
309See \l {QML Value Types} for a list of the types of properties that are
310supported by default. Additionally, any available \l {QML Object Types}
311{QML object type} may also be used as a property type.
312
313\section3 Special Property Types
314
315\section4 Object List Property Attributes
316
317A \l list type property can be assigned a list of QML object-type values.
318The syntax for defining an object list value is a comma-separated list
319surrounded by square brackets:
320
321\code
322 [ <item 1>, <item 2>, ... ]
323\endcode
324
325For example, the \l Item type has a \l {Item::states}{states} property that is
326used to hold a list of \l State type objects. The code below initializes the
327value of this property to a list of three \l State objects:
328
329\qml
330import QtQuick
331
332Item {
333 states: [
334 State { name: "loading" },
335 State { name: "running" },
336 State { name: "stopped" }
337 ]
338}
339\endqml
340
341If the list contains a single item, the square brackets may be omitted:
342
343\qml
344import QtQuick
345
346Item {
347 states: State { name: "running" }
348}
349\endqml
350
351A \l list type property may be specified in an object declaration with the
352following syntax:
353
354\code
355 [default] property list<<ObjectType>> propertyName
356\endcode
357
358and, like other property declarations, a property initialization may be
359combined with the property declaration with the following syntax:
360
361\code
362 [default] property list<<ObjectType>> propertyName: <value>
363\endcode
364
365An example of list property declaration follows:
366
367\qml
368import QtQuick
369
370Rectangle {
371 // declaration without initialization
372 property list<Rectangle> siblingRects
373
374 // declaration with initialization
375 property list<Rectangle> childRects: [
376 Rectangle { color: "red" },
377 Rectangle { color: "blue"}
378 ]
379}
380\endqml
381
382If you wish to declare a property to store a list of values which are not
383necessarily QML object-type values, you should declare a \l var property
384instead.
385
386
387\section4 Grouped Properties
388
389In some cases properties contain a logical group of sub-property attributes.
390These sub-property attributes can be assigned to using either the dot notation
391or group notation.
392
393For example, the \l Text type has a \l{Text::font.family}{font} group property. Below,
394the first \l Text object initializes its \c font values using dot notation,
395while the second uses group notation:
396
397\code
398Text {
399 //dot notation
400 font.pixelSize: 12
401 font.b: true
402}
403
404Text {
405 //group notation
406 font { pixelSize: 12; b: true }
407}
408\endcode
409
410Grouped property types are types which have subproperties. If a grouped property
411type is an object type (as opposed to a value type), the property that holds it
412must be read-only. This is to prevent you from replacing the object the
413subproperties belong to.
414
415\section3 Property Aliases
416
417Property aliases are properties which hold a reference to another property.
418Unlike an ordinary property definition, which allocates a new, unique storage
419space for the property, a property alias connects the newly declared property
420(called the aliasing property) as a direct reference to an existing property
421(the aliased property).
422
423A property alias declaration looks like an ordinary property definition, except
424that it requires the \c alias keyword instead of a property type, and the
425right-hand-side of the property declaration must be a valid alias reference:
426
427\code
428[default] property alias <name>: <alias reference>
429\endcode
430
431Unlike an ordinary property, an alias has the following restrictions:
432
433\list
434\li It can only refer to an object, or the
435 property of an object, that is within the scope of the \l{QML Object Types}
436 {type} within which the alias is declared.
437\li It cannot contain arbitrary
438 JavaScript expressions
439\li It cannot refer to objects declared outside of
440 the scope of its type.
441\li The \e {alias reference} is not optional,
442 unlike the optional default value for an ordinary property; the alias reference
443 must be provided when the alias is first declared.
444\li It cannot refer to \l {Attached Properties and Attached Signal Handlers}
445 {attached properties}.
446\li It cannot refer to properties inside a hierarchy with depth 3 or greater. The
447 following code will not work:
448 \code
449 property alias color: myItem.myRect.border.color
450
451 Item {
452 id: myItem
453 property Rectangle myRect
454 }
455 \endcode
456
457 However, aliases to properties that are up to two levels deep will work.
458
459 \code
460 property alias color: rectangle.border.color
461
462 Rectangle {
463 id: rectangle
464 }
465 \endcode
466\endlist
467
468For example, below is a \c Button type with a \c buttonText aliased property
469which is connected to the \c text object of the \l Text child:
470
471\qml
472// Button.qml
473import QtQuick
474
475Rectangle {
476 property alias buttonText: textItem.text
477
478 width: 100; height: 30; color: "yellow"
479
480 Text { id: textItem }
481}
482\endqml
483
484The following code would create a \c Button with a defined text string for the
485child \l Text object:
486
487\qml
488Button { buttonText: "Click Me" }
489\endqml
490
491Here, modifying \c buttonText directly modifies the textItem.text value; it
492does not change some other value that then updates textItem.text. If
493\c buttonText was not an alias, changing its value would not actually change
494the displayed text at all, as property bindings are not bi-directional: the
495\c buttonText value would have changed if textItem.text was changed, but not
496the other way around.
497
498
499\section4 Considerations for Property Aliases
500
501It is possible for an aliasing property to have the same name as an existing
502property, effectively overwriting the existing property. For example,
503the following QML type has a \c color alias property, named the same as the
504built-in \l {Rectangle::color} property:
505
506\snippet qml/properties.qml alias overwrite
507
508Any object that use this type and refer to its \c color property will be
509referring to the alias rather than the ordinary \l {Rectangle::color} property.
510Internally, however, the rectangle can correctly set its \c color
511property and refer to the actual defined property rather than the alias.
512
513
514\section4 Property Aliases and Types
515
516Property aliases cannot have explicit type specifications. The type of a
517property alias is the \e declared type of the property or object it refers to.
518Therefore, if you create an alias to an object referenced via id with extra
519properties declared inline, the extra properties won't be accessible through
520the alias:
521
522\qml
523// MyItem.qml
524Item {
525 property alias inner: innerItem
526
527 Item {
528 id: innerItem
529 property int extraProperty
530 }
531}
532\endqml
533
534You cannot initialize \a inner.extraProperty from outside of this component, as
535inner is only an \a Item:
536
537\qml
538// main.qml
539MyItem {
540 inner.extraProperty: 5 // fails
541}
542\endqml
543
544However, if you extract the inner object into a separate component with a
545dedicated .qml file, you can instantiate that component instead and have all
546its properties available through the alias:
547
548\qml
549// MainItem.qml
550Item {
551 // Now you can access inner.extraProperty, as inner is now an ExtraItem
552 property alias inner: innerItem
553
554 ExtraItem {
555 id: innerItem
556 }
557}
558
559// ExtraItem.qml
560Item {
561 property int extraProperty
562}
563\endqml
564
565\section3 Default Properties
566
567An object definition can have a single \e default property. A default property
568is the property to which a value is assigned if an object is declared within
569another object's definition without declaring it as a value for a particular
570property.
571
572Declaring a property with the optional \c default keyword marks it as the
573default property. For example, say there is a file MyLabel.qml with a default
574property \c someText:
575
576\qml
577// MyLabel.qml
578import QtQuick
579
580Text {
581 default property var someText
582
583 text: `Hello, ${someText.text}`
584}
585\endqml
586
587The \c someText value could be assigned to in a \c MyLabel object definition,
588like this:
589
590\qml
591MyLabel {
592 Text { text: "world!" }
593}
594\endqml
595
596This has exactly the same effect as the following:
597
598\qml
599MyLabel {
600 someText: Text { text: "world!" }
601}
602\endqml
603
604However, since the \c someText property has been marked as the default
605property, it is not necessary to explicitly assign the \l Text object
606to this property.
607
608You will notice that child objects can be added to any \l {Item}-based type
609without explicitly adding them to the \l {Item::children}{children} property.
610This is because the default property of \l Item is its \c data property, and
611any items added to this list for an \l Item are automatically added to its
612list of \l {Item::children}{children}.
613
614Default properties can be useful for reassigning the children of an item.
615For example:
616
617\qml
618Item {
619 default property alias content: inner.children
620
621 Item {
622 id: inner
623 }
624}
625\endqml
626
627By setting the default property \e alias to \c {inner.children}, any object
628assigned as a child of the outer item is automatically reassigned as a child
629of the inner item.
630
631\warning Setting the values of a an element's default list property can be done implicitly or
632explicitly. Within a single element's definition, these two methods must not be mixed as that leads
633to undefined ordering of the elements in the list.
634
635\qml
636Item {
637 // Use either implicit or explicit assignement to the default list property but not both!
638 Rectangle { width: 40 } // implicit
639 data: [ Rectangle { width: 100 } ] // explicit
640}
641\endqml
642
643\section3 Required Properties
644
645An object declaration may define a property as required, using the \c required
646keyword. The syntax is
647\code
648 required property <propertyType> <propertyName>
649\endcode
650
651As the name suggests, required properties must be set when an instance of the object
652is created. Violation of this rule will result in QML applications not starting if it can be
653detected statically. In case of dynamically instantiated QML components (for instance via
654\l {QtQml::Qt::createComponent()}{Qt.createComponent()}), violating this rule results in a
655warning and a null return value.
656
657It's possible to make an existing property required with
658\code
659 required <propertyName>
660\endcode
661The following example shows how to create a custom Rectangle component, in which the color
662property always needs to be specified.
663\qml
664// ColorRectangle.qml
665Rectangle {
666 required color
667}
668\endqml
669
670\note You can't assign an initial value to a required property from QML, as that would go
671directly against the intended usage of required properties.
672
673Required properties play a special role in model-view-delegate code:
674If the delegate of a view has required properties whose names match with
675the role names of the view's model, then those properties will be initialized
676with the model's corresponding values.
677For more information, visit the \l{Models and Views in Qt Quick} page.
678
679See \l{QQmlComponent::createWithInitialProperties}, \l{QQmlApplicationEngine::setInitialProperties}
680and \l{QQuickView::setInitialProperties} for ways to initialize required properties from C++.
681
682\section3 Read-Only Properties
683
684An object declaration may define a read-only property using the \c readonly
685keyword, with the following syntax:
686
687\code
688 readonly property <propertyType> <propertyName> : <value>
689\endcode
690
691Read-only properties must be assigned a static value or a binding expression on
692initialization. After a read-only property is initialized, you cannot change
693its static value or binding expression anymore.
694
695For example, the code in the \c Component.onCompleted block below is invalid:
696
697\qml
698Item {
699 readonly property int someNumber: 10
700
701 Component.onCompleted: someNumber = 20 // TypeError: Cannot assign to read-only property
702}
703\endqml
704
705\note A read-only property cannot also be a \l{Default Properties}{default}
706property.
707
708
709\section3 Property Modifier Objects
710
711Properties can have
712\l{qtqml-cppintegration-definetypes.html#property-modifier-types}
713{property value modifier objects} associated with them.
714The syntax for declaring an instance of a property modifier type associated
715with a particular property is as follows:
716
717\code
718<PropertyModifierTypeName> on <propertyName> {
719 // attributes of the object instance
720}
721\endcode
722
723This is commonly referred to as "on" syntax.
724
725It is important to note that the above syntax is in fact an
726\l{qtqml-syntax-basics.html#object-declarations}{object declaration} which
727will instantiate an object which acts on a pre-existing property.
728
729Certain property modifier types may only be applicable to specific property
730types, however this is not enforced by the language. For example, the
731\c NumberAnimation type provided by \c QtQuick will only animate
732numeric-type (such as \c int or \c real) properties. Attempting to use a
733\c NumberAnimation with non-numeric property will not result in an error,
734however the non-numeric property will not be animated. The behavior of a
735property modifier type when associated with a particular property type is
736defined by its implementation.
737
738
739\section2 Signal Attributes
740
741A signal is a notification from an object that some event has occurred: for
742example, a property has changed, an animation has started or stopped, or
743when an image has been downloaded. The \l MouseArea type, for example, has
744a \l {MouseArea::}{clicked} signal that is emitted when the user clicks
745within the mouse area.
746
747An object can be notified through a \l{Signal handler attributes}
748{signal handler} whenever a particular signal is emitted. A signal handler
749is declared with the syntax \e on<Signal> where \e <Signal> is the name of the
750signal, with the first letter capitalized. The signal handler must be declared
751within the definition of the object that emits the signal, and the handler
752should contain the block of JavaScript code to be executed when the signal
753handler is invoked.
754
755For example, the \e onClicked signal handler below is declared within the
756\l MouseArea object definition, and is invoked when the \l MouseArea is
757clicked, causing a console message to be printed:
758
759\qml
760import QtQuick
761
762Item {
763 width: 100; height: 100
764
765 MouseArea {
766 anchors.fill: parent
767 onClicked: {
768 console.log("Click!")
769 }
770 }
771}
772\endqml
773
774\section3 Defining Signal Attributes
775
776A signal may be defined for a type in C++ by registering a Q_SIGNAL of a class
777which is then registered with the QML type system. Alternatively, a custom
778signal for an object type may be defined in an object declaration in a QML
779document with the following syntax:
780
781\code
782 signal <signalName>[([<parameterName>: <parameterType>[, ...]])]
783\endcode
784
785Attempting to declare two signals or methods with the same name in the same
786type block is an error. However, a new signal may reuse the name of an existing
787signal on the type. (This should be done with caution, as the existing signal
788may be hidden and become inaccessible.)
789
790Here are three examples of signal declarations:
791
792\qml
793import QtQuick
794
795Item {
796 signal clicked
797 signal hovered()
798 signal actionPerformed(action: string, actionResult: int)
799}
800\endqml
801
802You can also specify signal parameters in property style syntax:
803
804\qml
805signal actionCanceled(string action)
806\endqml
807
808In order to be consistent with method declarations, you should prefer the
809type declarations using colons.
810
811If the signal has no parameters, the "()" brackets are optional. If parameters
812are used, the parameter types must be declared, as for the \c string and \c int
813arguments for the \c actionPerformed signal above. The allowed parameter types
814are the same as those listed under \l {Defining Property Attributes} on this page.
815
816To emit a signal, invoke it as a method. Any relevant
817\l{Signal handler attributes}{signal handlers} will be invoked when the signal
818is emitted, and handlers can use the defined signal argument names to access
819the respective arguments.
820
821\section3 Property Change Signals
822
823QML types also provide built-in \e {property change signals} that are emitted
824whenever a property value changes, as previously described in the section on
825\l{Property attributes}{property attributes}. See the upcoming section on
826\l{Property change signal handlers}{property change signal handlers} for more
827information about why these signals are useful, and how to use them.
828
829
830\section2 Signal Handler Attributes
831
832Signal handlers are a special sort of \l{Method attributes}{method attribute},
833where the method implementation is invoked by the QML engine whenever the
834associated signal is emitted. Adding a signal to an object definition in QML
835will automatically add an associated signal handler to the object definition,
836which has, by default, an empty implementation. Clients can provide an
837implementation, to implement program logic.
838
839Consider the following \c SquareButton type, whose definition is provided in
840the \c SquareButton.qml file as shown below, with signals \c activated and
841\c deactivated:
842
843\qml
844// SquareButton.qml
845Rectangle {
846 id: root
847
848 signal activated(xPosition: real, yPosition: real)
849 signal deactivated
850
851 property int side: 100
852 width: side; height: side
853
854 MouseArea {
855 anchors.fill: parent
856 onReleased: root.deactivated()
857 onPressed: mouse => root.activated(mouse.x, mouse.y)
858 }
859}
860\endqml
861
862These signals could be received by any \c SquareButton objects in another QML
863file in the same directory, where implementations for the signal handlers are
864provided by the client:
865
866\qml
867// myapplication.qml
868SquareButton {
869 onDeactivated: console.log("Deactivated!")
870 onActivated: (xPosition, yPosition) => {
871 console.log(`Activated at ${xPosition}, ${yPosition}`)
872 }
873}
874\endqml
875
876Signal handlers don't have to declare their parameter types because the signal
877already specifies them. The arrow function syntax shown above does not support
878type annotations.
879
880See the \l {Signal and Handler Event System} for more details on use of
881signals.
882
883\section3 Property Change Signal Handlers
884
885Signal handlers for property change signal take the syntax form
886\e on<Property>Changed where \e <Property> is the name of the property,
887with the first letter capitalized. For example, although the \l TextInput type
888documentation does not document a \c textChanged signal, this signal is
889implicitly available through the fact that \l TextInput has a
890\l {TextInput::text}{text} property and so it is possible to write an
891\c onTextChanged signal handler to be called whenever this property changes:
892
893\qml
894import QtQuick
895
896TextInput {
897 text: "Change this!"
898
899 onTextChanged: console.log(`Text has changed to: ${text}`)
900}
901\endqml
902
903
904\section2 Method Attributes
905
906A method of an object type is a function which may be called to perform some
907processing or trigger further events. A method can be connected to a signal so
908that it is automatically invoked whenever the signal is emitted. See
909\l {Signal and Handler Event System} for more details.
910
911\section3 Defining Method Attributes
912
913A method may be defined for a type in C++ by tagging a function of a class
914which is then registered with the QML type system with Q_INVOKABLE or by
915registering it as a Q_SLOT of the class. Alternatively, a custom method can
916be added to an object declaration in a QML document with the following syntax:
917
918\code
919 function <functionName>([<parameterName>[: <parameterType>][, ...]]) [: <returnType>] { <body> }
920\endcode
921
922Methods can be added to a QML type in order to define standalone, reusable
923blocks of JavaScript code. These methods can be invoked either internally or
924by external objects.
925
926Unlike signals, method parameter types do not have to be declared as they
927default to the \c var type. You should, however, declare them in order to
928help qmlcachegen generate more performant code, and to improve maintainability.
929
930Attempting to declare two methods or signals with the same name in the same
931type block is an error. However, a new method may reuse the name of an existing
932method on the type. (This should be done with caution, as the existing method
933may be hidden and become inaccessible.)
934
935Below is a \l Rectangle with a \c calculateHeight() method that is called when
936assigning the \c height value:
937
938\qml
939import QtQuick
940Rectangle {
941 id: rect
942
943 function calculateHeight(): real {
944 return rect.width / 2;
945 }
946
947 width: 100
948 height: calculateHeight()
949}
950\endqml
951
952If the method has parameters, they are accessible by name within the method.
953Below, when the \l MouseArea is clicked it invokes the \c moveTo() method which
954can then refer to the received \c newX and \c newY parameters to reposition the
955text:
956
957\qml
958import QtQuick
959
960Item {
961 width: 200; height: 200
962
963 MouseArea {
964 anchors.fill: parent
965 onClicked: mouse => label.moveTo(mouse.x, mouse.y)
966 }
967
968 Text {
969 id: label
970
971 function moveTo(newX: real, newY: real) {
972 label.x = newX;
973 label.y = newY;
974 }
975
976 text: "Move me!"
977 }
978}
979\endqml
980
981
982\section2 Attached Properties and Attached Signal Handlers
983
984\e {Attached properties} and \e {attached signal handlers} are mechanisms that
985enable objects to be annotated with extra properties or signal handlers that
986are otherwise unavailable to the object. In particular, they allow objects to
987access properties or signals that are specifically relevant to the individual
988object.
989
990A QML type implementation may choose to \l {Providing Attached Properties}{create an \e {attaching type} in C++} with
991particular properties and signals. Instances of this type can then be created
992and \e attached to specific objects at run time, allowing those objects to
993access the properties and signals of the attaching type. These are accessed by
994prefixing the properties and respective signal handlers with the name of the
995attaching type.
996
997References to attached properties and handlers take the following syntax form:
998
999\code
1000<AttachingType>.<propertyName>
1001<AttachingType>.on<SignalName>
1002\endcode
1003
1004For example, the \l ListView type has an attached property
1005\l {ListView::isCurrentItem}{ListView.isCurrentItem} that is available to each delegate object in a
1006ListView. This can be used by each individual delegate object to determine
1007whether it is the currently selected item in the view:
1008
1009\qml
1010import QtQuick
1011
1012ListView {
1013 width: 240; height: 320
1014 model: 3
1015 delegate: Rectangle {
1016 width: 100; height: 30
1017 color: ListView.isCurrentItem ? "red" : "yellow"
1018 }
1019}
1020\endqml
1021
1022In this case, the name of the \e {attaching type} is \c ListView and the
1023property in question is \c isCurrentItem, hence the attached property is
1024referred to as \c ListView.isCurrentItem.
1025
1026An attached signal handler is referred to in the same way. For example, the
1027\l{Component::completed}{Component.onCompleted} attached signal handler is
1028commonly used to execute some JavaScript code when a component's creation
1029process has been completed. In the example below, once the \l ListModel has
1030been fully created, its \c Component.onCompleted signal handler will
1031automatically be invoked to populate the model:
1032
1033\qml
1034import QtQuick
1035
1036ListView {
1037 width: 240; height: 320
1038 model: ListModel {
1039 id: listModel
1040 Component.onCompleted: {
1041 for (let i = 0; i < 10; i++) {
1042 append({ Name: `Item ${i}` })
1043 }
1044 }
1045 }
1046 delegate: Text { text: index }
1047}
1048\endqml
1049
1050Since the name of the \e {attaching type} is \c Component and that type has a
1051\l{Component::completed}{completed} signal, the attached signal handler is
1052referred to as \c Component.onCompleted.
1053
1054
1055\section3 A Note About Accessing Attached Properties and Signal Handlers
1056
1057A common error is to assume that attached properties and signal handlers are
1058directly accessible from the children of the object to which these attributes
1059have been attached. This is not the case. The instance of the
1060\e {attaching type} is only attached to specific objects, not to the object
1061and all of its children.
1062
1063For example, below is a modified version of the earlier example involving
1064attached properties. This time, the delegate is an \l Item and the colored
1065\l Rectangle is a child of that item:
1066
1067\qml
1068import QtQuick
1069
1070ListView {
1071 width: 240; height: 320
1072 model: 3
1073 delegate: Item {
1074 width: 100; height: 30
1075
1076 Rectangle {
1077 width: 100; height: 30
1078 color: ListView.isCurrentItem ? "red" : "yellow" // WRONG! This won't work.
1079 }
1080 }
1081}
1082\endqml
1083
1084This does not work as expected because \c ListView.isCurrentItem is attached
1085\e only to the root delegate object, and not its children. Since the
1086\l Rectangle is a child of the delegate, rather than being the delegate itself,
1087it cannot access the \c isCurrentItem attached property as
1088\c ListView.isCurrentItem. So instead, the rectangle should access
1089\c isCurrentItem through the root delegate:
1090
1091\qml
1092ListView {
1093 delegate: Item {
1094 id: delegateItem
1095 width: 100; height: 30
1096
1097 Rectangle {
1098 width: 100; height: 30
1099 color: delegateItem.ListView.isCurrentItem ? "red" : "yellow" // correct
1100 }
1101 }
1102}
1103\endqml
1104
1105Now \c delegateItem.ListView.isCurrentItem correctly refers to the
1106\c isCurrentItem attached property of the delegate.
1107
1108\section2 Enumeration Attributes
1109
1110Enumerations provide a fixed set of named choices. They can be declared in QML using the \c enum keyword:
1111
1112\qml
1113// MyText.qml
1114Text {
1115 enum TextType {
1116 Normal,
1117 Heading
1118 }
1119}
1120\endqml
1121
1122As shown above, enumeration types (e.g. \c TextType) and values (e.g. \c Normal) must begin with an uppercase letter.
1123
1124Values are referred to via \c {<Type>.<EnumerationType>.<Value>} or \c {<Type>.<Value>}.
1125
1126\qml
1127// MyText.qml
1128Text {
1129 enum TextType {
1130 Normal,
1131 Heading
1132 }
1133
1134 property int textType: MyText.TextType.Normal
1135
1136 font.bold: textType === MyText.TextType.Heading
1137 font.pixelSize: textType === MyText.TextType.Heading ? 24 : 12
1138}
1139\endqml
1140
1141More information on enumeration usage in QML can be found in the \l {QML Value Types} \l enumeration documentation.
1142
1143The ability to declare enumerations in QML was introduced in Qt 5.10.
1144
1145*/