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