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. To react to the signal,
128declare a \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
297The QML engine cannot evaluate every binding at the start of object creation.
298The engine evaluates such bindings later, and this first evaluation assigns a
299value to the property. The assignment can emit the property's change signal.
300
301\note To assign a binding expression imperatively, the binding expression
302must be contained in a function that is passed into \l{Qt::binding()}{Qt.binding()},
303and then the value returned by Qt.binding() must be assigned to the property.
304In contrast, Qt.binding() must not be used when assigning a binding expression
305upon initialization. See \l{Property Binding} for more information.
306
307
308\section3 Type Safety
309
310Properties are type safe. A property can only be assigned a value that matches
311the property type.
312
313For example, if a property is an int, and if you try to assign a string to it,
314you will get an error:
315
316\code
317property int volume: "four" // generates an error; the property's object will not be loaded
318\endcode
319
320Likewise if a property is assigned a value of the wrong type during run time,
321the new value will not be assigned, and an error will be generated.
322
323Some property types do not have a natural
324value representation, and for those property types the QML engine
325automatically performs string-to-typed-value conversion. So, for example,
326even though properties of the \c color type store colors and not strings,
327you are able to assign the string \c "red" to a color property, without an
328error being reported.
329
330See \l {QML Value Types} for a list of the types of properties that are
331supported by default. Additionally, any available \l {QML Object Types}
332{QML object type} may also be used as a property type.
333
334\section3 Special Property Types
335
336\section4 Object List Property Attributes
337
338A \l list type property can be assigned a list of QML object-type values.
339The syntax for defining an object list value is a comma-separated list
340surrounded by square brackets:
341
342\code
343 [ <item 1>, <item 2>, ... ]
344\endcode
345
346For example, the \l Item type has a \l {Item::states}{states} property that is
347used to hold a list of \l State type objects. The code below initializes the
348value of this property to a list of three \l State objects:
349
350\qml
351import QtQuick
352
353Item {
354 states: [
355 State { name: "loading" },
356 State { name: "running" },
357 State { name: "stopped" }
358 ]
359}
360\endqml
361
362If the list contains a single item, the square brackets may be omitted:
363
364\qml
365import QtQuick
366
367Item {
368 states: State { name: "running" }
369}
370\endqml
371
372A \l list type property may be specified in an object declaration with the
373following syntax:
374
375\code
376 [default] property list<<ObjectType>> propertyName
377\endcode
378
379and, like other property declarations, a property initialization may be
380combined with the property declaration with the following syntax:
381
382\code
383 [default] property list<<ObjectType>> propertyName: <value>
384\endcode
385
386An example of list property declaration follows:
387
388\qml
389import QtQuick
390
391Rectangle {
392 // declaration without initialization
393 property list<Rectangle> siblingRects
394
395 // declaration with initialization
396 property list<Rectangle> childRects: [
397 Rectangle { color: "red" },
398 Rectangle { color: "blue"}
399 ]
400}
401\endqml
402
403If you wish to declare a property to store a list of values which are not
404necessarily QML object-type values, you should declare a \l var property
405instead.
406
407
408\section4 Grouped Properties
409
410In some cases properties contain a logical group of sub-property attributes.
411These sub-property attributes can be assigned to using either the dot notation
412or group notation.
413
414For example, the \l Text type has a \c font property.
415Below, the first \l Text object initializes its \c font values using
416dot notation, while the second uses group notation:
417
418\code
419Text {
420 //dot notation
421 font.pixelSize: 12
422 font.bold: true
423}
424
425Text {
426 //group notation
427 font { pixelSize: 12; bold: true }
428}
429\endcode
430
431Grouped property syntax is available for any property whose type has
432sub-properties of its own. It is a notation, not a separate kind of property:
433whether the property holds a \l{QML Value Types}{value type} like \c font or
434an \l{QML Object Types}{object type} makes no difference to the syntax.
435
436The type of the property does affect what the engine has to do, though:
437
438\list
439\li If the property holds a value type, the engine reads the value, modifies
440 it, and writes it back. The property therefore has to be writable.
441\li If the property holds an object type, the assignments are written to the
442 object that the property currently holds. That object must not be null when
443 the assignments are applied. The property itself may be read-only or
444 writable. Making it read-only is a way to keep QML code from replacing the
445 object the sub-properties belong to, thus avoiding confusion over what
446 object the grouped properties apply to. It is generally a good idea.
447\endlist
448
449Sub-property names are resolved against the property's declared type, not
450against the type of the object it holds at run time. You also cannot use both
451forms for the same property in the same object definition: either assign an
452object to the property, or assign to its sub-properties.
453
454\section3 Property Aliases
455
456Property aliases are properties which hold a reference to another property.
457Unlike an ordinary property definition, which allocates a new, unique storage
458space for the property, a property alias connects the newly declared property
459(called the aliasing property) as a direct reference to an existing property
460(the aliased property).
461
462A property alias declaration looks like an ordinary property definition, except
463that it requires the \c alias keyword instead of a property type, and the
464right-hand-side of the property declaration must be a valid alias reference:
465
466\code
467[default] property alias <name>: <alias reference>
468\endcode
469
470Unlike an ordinary property, an alias has the following restrictions:
471
472\list
473\li It can only refer to an object, or the
474 property of an object, that is within the scope of the \l{QML Object Types}
475 {type} within which the alias is declared.
476\li It cannot contain arbitrary
477 JavaScript expressions
478\li It cannot refer to objects declared outside of
479 the scope of its type.
480\li The \e {alias reference} is not optional,
481 unlike the optional default value for an ordinary property; the alias reference
482 must be provided when the alias is first declared.
483\li It cannot refer to \l {Attached Properties and Attached Signal Handlers}
484 {attached properties}.
485\li It cannot refer to properties inside a hierarchy with depth 3 or greater. The
486 following code will not work:
487 \code
488 property alias color: myItem.myRect.border.color
489
490 Item {
491 id: myItem
492 property Rectangle myRect
493 }
494 \endcode
495
496 However, aliases to properties that are up to two levels deep will work.
497
498 \code
499 property alias color: rectangle.border.color
500
501 Rectangle {
502 id: rectangle
503 }
504 \endcode
505\endlist
506
507For example, below is a \c Button type with a \c buttonText aliased property
508which is connected to the \c text object of the \l Text child:
509
510\qml
511// Button.qml
512import QtQuick
513
514Rectangle {
515 property alias buttonText: textItem.text
516
517 width: 100; height: 30; color: "yellow"
518
519 Text { id: textItem }
520}
521\endqml
522
523The following code would create a \c Button with a defined text string for the
524child \l Text object:
525
526\qml
527Button { buttonText: "Click Me" }
528\endqml
529
530Here, modifying \c buttonText directly modifies the textItem.text value; it
531does not change some other value that then updates textItem.text. If
532\c buttonText was not an alias, changing its value would not actually change
533the displayed text at all, as property bindings are not bi-directional: the
534\c buttonText value would have changed if textItem.text was changed, but not
535the other way around.
536
537\section4 Property Aliases and Change Notification
538
539As with an ordinary property, declaring a property alias implicitly creates a
540value-change \l{Signal attributes}{signal} for the alias. To react to the
541signal, declare a \l{Signal handler attributes}{signal handler} called
542\e on<AliasName>Changed, where \e <AliasName> is the name of the alias, with
543the first letter capitalized.
544
545The alias's change signal is emitted whenever the value of the aliased property
546changes, regardless of whether the change comes through the alias or through
547the aliased property directly. In the \c Button example above, \c Button emits
548\c buttonTextChanged whenever \c textItem.text changes, and an
549\c onButtonTextChanged handler responds to those changes just as it would for an
550ordinary property.
551
552If the alias refers to a property of an object implemented in C++, change
553notification requires that property to have a \c NOTIFY signal or to be
554\l{Qt Bindable Properties}{bindable}, the same as for an ordinary property.
555Without a \c NOTIFY signal or a bindable interface, neither the property nor
556the alias emits a change signal.
557
558An alias declaration assigns no value. It only refers to a property that
559already exists. The declaration itself does not emit a change signal.
560
561\section4 Property Aliases and Types
562
563Property aliases cannot have explicit type specifications. The type of a
564property alias is the \e declared type of the property or object it refers to.
565Therefore, if you create an alias to an object referenced via id with extra
566properties declared inline, the extra properties won't be accessible through
567the alias:
568
569\qml
570// MyItem.qml
571Item {
572 property alias inner: innerItem
573
574 Item {
575 id: innerItem
576 property int extraProperty
577 }
578}
579\endqml
580
581You cannot initialize \a inner.extraProperty from outside of this component, as
582inner is only an \a Item:
583
584\qml
585// main.qml
586MyItem {
587 inner.extraProperty: 5 // fails
588}
589\endqml
590
591However, if you extract the inner object into a separate component with a
592dedicated .qml file, you can instantiate that component instead and have all
593its properties available through the alias:
594
595\qml
596// MainItem.qml
597Item {
598 // Now you can access inner.extraProperty, as inner is now an ExtraItem
599 property alias inner: innerItem
600
601 ExtraItem {
602 id: innerItem
603 }
604}
605
606// ExtraItem.qml
607Item {
608 property int extraProperty
609}
610\endqml
611
612\section3 Default Properties
613
614An object definition can have a single \e default property. When one object
615is nested directly inside another object without specifying a property,
616it is automatically assigned to the enclosing object's default property.
617
618Declaring a property with the optional \c default keyword marks it as the
619default property. For example, say there is a file Framer.qml with a default
620property \c focusItem:
621
622\qml
623// Framer.qml
624import QtQuick
625
626Row {
627 default property Item focusItem
628 property Item leftItem: Rectangle {
629 width: 10
630 height: parent.height
631 color: "red"
632 }
633 property Item rightItem: Rectangle {
634 width: 10
635 height: parent.height
636 color: "blue"
637 }
638 children: [leftItem, focusItem, rightItem]
639}
640\endqml
641
642The \c focusItem value could be assigned to in a \c Framer object
643definition, like this:
644
645\qml
646Framer {
647 Text { text: "Hello, world!" }
648}
649\endqml
650
651This has exactly the same effect as the following:
652
653\qml
654Framer {
655 focusItem: Text { text: "Hello, world!" }
656}
657\endqml
658
659However, since the \c focusItem property has been marked as the default
660property, it is not necessary to explicitly assign the \l Text object
661to this property.
662
663While a property of any type can be marked as a \c default property,
664it is generally only helpful to mark properties of type \c var, of \l{QML
665Object Types}{object type}, and their respective \l{QML Sequence
666Types}{sequence types}: As only object instances are
667assigned to the default property, there is no benefit in QML to having for
668example a \c default string property.
669
670Consider the following TextHolder type:
671
672\qml *
673// TextHolder.qml
674Item {
675 property default string mytext
676}
677\endqml
678By itself, this is fine. However, one cannot assign a string literal to
679\c mytext without explicitly mentioning the property name:
680\qml
681TextHolder {
682 /* The following would be a syntax error, and will not assign
683 to the mytext property:
684 "some text"
685
686 The line below is the only way to assign the value:
687 \1/
688 mytext: "some text"
689}
690\endqml
691
692You will notice that child objects can be added to any \l {Item}-based type
693without explicitly adding them to the \l {Item::children}{children} property.
694This is because the default property of \l Item is its \c data property, and
695any items added to this list for an \l Item are automatically added to its
696list of \l {Item::children}{children}.
697
698Default properties can be useful for reassigning the children of an item.
699For example:
700
701\qml
702Item {
703 default property alias content: inner.children
704
705 Item {
706 id: inner
707 }
708}
709\endqml
710
711By setting the default property \e alias to \c {inner.children}, any object
712assigned as a child of the outer item is automatically reassigned as a child
713of the inner item.
714
715\warning Setting the values of a an element's default list property can be done implicitly or
716explicitly. Within a single element's definition, these two methods must not be mixed as that leads
717to undefined ordering of the elements in the list.
718
719\qml
720Item {
721 // Use either implicit or explicit assignement to the default list property but not both!
722 Rectangle { width: 40 } // implicit
723 data: [ Rectangle { width: 100 } ] // explicit
724}
725\endqml
726
727\section3 Override Semantics
728
729By default, properties can be \e shadowed: You re-declare a property in a derived QML type,
730possibly with a new type and new attributes. This results in two properties of the same name,
731only one of which is accessible in any given context. This is rarely what you want. Often it's
732accidental, and most of the time the effects are quite confusing. Additionally, shadowing is bad
733for tooling.
734
735To address this, the \c virtual, \c override, \c final keywords and additional warnings and errors
736were introduced.
737
738For more details and a comprehensive set of examples, including warnings and errors,
739see the \l{qtqml-syntax-overridesemantics.html}{Property Shadowing and Override Semantics} page.
740
741\section3 Required Properties
742
743An object declaration may define a property as required, using the \c required
744keyword. The syntax is
745\code
746 required property <propertyType> <propertyName>
747\endcode
748
749As the name suggests, required properties must be set when an instance of the object
750is created. Violation of this rule will result in QML applications not starting if it can be
751detected statically. In case of dynamically instantiated QML components (for instance via
752\l {QtQml::Qt::createComponent()}{Qt.createComponent()}), violating this rule results in a
753warning and a null return value.
754
755It's possible to make an existing property required with
756\code
757 required <propertyName>
758\endcode
759The following example shows how to create a custom Rectangle component, in which the color
760property always needs to be specified.
761\qml
762// ColorRectangle.qml
763Rectangle {
764 required color
765}
766\endqml
767
768\note You can't assign an initial value to a required property from QML, as that would go
769directly against the intended usage of required properties.
770
771Required properties play a special role in model-view-delegate code:
772If the delegate of a view has required properties whose names match with
773the role names of the view's model, then those properties will be initialized
774with the model's corresponding values.
775For more information, visit the \l{Models and Views in Qt Quick} page.
776
777See \l{QQmlComponent::createWithInitialProperties}, \l{QQmlApplicationEngine::setInitialProperties}
778and \l{QQuickView::setInitialProperties} for ways to initialize required properties from C++.
779
780\section3 Read-Only Properties
781
782An object declaration may define a read-only property using the \c readonly
783keyword, with the following syntax:
784
785\code
786 readonly property <propertyType> <propertyName> : <value>
787\endcode
788
789Read-only properties must be assigned a static value or a binding expression on
790initialization. After a read-only property is initialized, you cannot change
791its static value or binding expression anymore.
792
793For example, the code in the \c Component.onCompleted block below is invalid:
794
795\qml
796Item {
797 readonly property int someNumber: 10
798
799 Component.onCompleted: someNumber = 20 // TypeError: Cannot assign to read-only property
800}
801\endqml
802
803\note A read-only property cannot also be a \l{#Default Properties}{default}
804property.
805
806\section3 Property Modifier Objects
807
808Properties can have
809\l{qtqml-cppintegration-definetypes.html#property-modifier-types}
810{property value modifier objects} associated with them.
811The syntax for declaring an instance of a property modifier type associated
812with a particular property is as follows:
813
814\code
815<PropertyModifierTypeName> on <propertyName> {
816 // attributes of the object instance
817}
818\endcode
819
820This is commonly referred to as "on" syntax.
821
822It is important to note that the above syntax is in fact an
823\l{qtqml-syntax-basics.html#object-declarations}{object declaration} which
824will instantiate an object which acts on a pre-existing property.
825
826Certain property modifier types may only be applicable to specific property
827types, however this is not enforced by the language. For example, the
828\c NumberAnimation type provided by \c QtQuick will only animate
829numeric-type (such as \c int or \c real) properties. Attempting to use a
830\c NumberAnimation with non-numeric property will not result in an error,
831however the non-numeric property will not be animated. The behavior of a
832property modifier type when associated with a particular property type is
833defined by its implementation.
834
835
836\section2 Signal Attributes
837
838A signal is a notification from an object that some event has occurred: for
839example, a property has changed, an animation has started or stopped, or
840when an image has been downloaded. The \l MouseArea type, for example, has
841a \l {MouseArea::}{clicked} signal that is emitted when the user clicks
842within the mouse area.
843
844An object can be notified through a \l{Signal handler attributes}
845{signal handler} whenever a particular signal is emitted. A signal handler
846is declared with the syntax \e on<Signal> where \e <Signal> is the name of the
847signal, with the first letter capitalized. The signal handler must be declared
848within the definition of the object that emits the signal, and the handler
849should contain the block of JavaScript code to be executed when the signal
850handler is invoked.
851
852For example, the \e onClicked signal handler below is declared within the
853\l MouseArea object definition, and is invoked when the \l MouseArea is
854clicked, causing a console message to be printed:
855
856\qml
857import QtQuick
858
859Item {
860 width: 100; height: 100
861
862 MouseArea {
863 anchors.fill: parent
864 onClicked: {
865 console.log("Click!")
866 }
867 }
868}
869\endqml
870
871\section3 Defining Signal Attributes
872
873A signal may be defined for a type in C++ by registering a Q_SIGNAL of a class
874which is then registered with the QML type system. Alternatively, a custom
875signal for an object type may be defined in an object declaration in a QML
876document with the following syntax:
877
878\code
879 signal <signalName>[([<parameterName>: <parameterType>[, ...]])]
880\endcode
881
882Attempting to declare two signals or methods with the same name in the same
883type block is an error. However, a new signal may reuse the name of an existing
884signal on the type. (This should be done with caution, as the existing signal
885may be hidden and become inaccessible.)
886
887Here are three examples of signal declarations:
888
889\qml
890import QtQuick
891
892Item {
893 signal clicked
894 signal hovered()
895 signal actionPerformed(action: string, actionResult: int)
896}
897\endqml
898
899You can also specify signal parameters in property style syntax:
900
901\qml
902signal actionCanceled(string action)
903\endqml
904
905In order to be consistent with method declarations, you should prefer the
906type declarations using colons.
907
908If the signal has no parameters, the "()" brackets are optional. If parameters
909are used, the parameter types must be declared, as for the \c string and \c int
910arguments for the \c actionPerformed signal above. The allowed parameter types
911are the same as those listed under \l {Defining Property Attributes} on this page.
912
913To emit a signal, invoke it as a method. Any relevant
914\l{Signal handler attributes}{signal handlers} will be invoked when the signal
915is emitted, and handlers can use the defined signal argument names to access
916the respective arguments.
917
918\section3 Property Change Signals
919
920QML types also provide built-in \e {property change signals} that are emitted
921whenever a property value changes, as previously described in the section on
922\l{Property attributes}{property attributes}. See the upcoming section on
923\l{Property change signal handlers}{property change signal handlers} for more
924information about why these signals are useful, and how to use them.
925Property aliases provide change signals as well: an alias's change signal
926is emitted whenever the value of the aliased property changes. See
927\l{Property Aliases and Change Notification} for details.
928
929\section2 Signal Handler Attributes
930
931Signal handlers are a special sort of \l{Method attributes}{method attribute},
932where the method implementation is invoked by the QML engine whenever the
933associated signal is emitted. Adding a signal to an object definition in QML
934will automatically add an associated signal handler to the object definition,
935which has, by default, an empty implementation. Clients can provide an
936implementation, to implement program logic.
937
938Consider the following \c SquareButton type, whose definition is provided in
939the \c SquareButton.qml file as shown below, with signals \c activated and
940\c deactivated:
941
942\qml
943// SquareButton.qml
944Rectangle {
945 id: root
946
947 signal activated(xPosition: real, yPosition: real)
948 signal deactivated
949
950 property int side: 100
951 width: side; height: side
952
953 MouseArea {
954 anchors.fill: parent
955 onReleased: root.deactivated()
956 onPressed: mouse => root.activated(mouse.x, mouse.y)
957 }
958}
959\endqml
960
961These signals could be received by any \c SquareButton objects in another QML
962file in the same directory, where implementations for the signal handlers are
963provided by the client:
964
965\qml
966// myapplication.qml
967SquareButton {
968 onDeactivated: console.log("Deactivated!")
969 onActivated: (xPosition, yPosition) => {
970 console.log(`Activated at ${xPosition}, ${yPosition}`)
971 }
972}
973\endqml
974
975Signal handlers don't have to declare their parameter types because the signal
976already specifies them. The arrow function syntax shown above does not support
977type annotations.
978
979See the \l {Signal and Handler Event System} for more details on use of
980signals.
981
982\section3 Property Change Signal Handlers
983
984Signal handlers for property change signal take the syntax form
985\e on<Property>Changed where \e <Property> is the name of the property,
986with the first letter capitalized. For example, although the \l TextInput type
987documentation does not document a \c textChanged signal, this signal is
988implicitly available through the fact that \l TextInput has a
989\l {TextInput::text}{text} property and so it is possible to write an
990\c onTextChanged signal handler to be called whenever this property changes:
991
992\qml
993import QtQuick
994
995TextInput {
996 text: "Change this!"
997
998 onTextChanged: console.log(`Text has changed to: ${text}`)
999}
1000\endqml
1001
1002
1003\section2 Method Attributes
1004
1005A method of an object type is a function which may be called to perform some
1006processing or trigger further events. A method can be connected to a signal so
1007that it is automatically invoked whenever the signal is emitted. See
1008\l {Signal and Handler Event System} for more details.
1009
1010\section3 Defining Method Attributes
1011
1012A method may be defined for a type in C++ by tagging a function of a class
1013which is then registered with the QML type system with Q_INVOKABLE or by
1014registering it as a Q_SLOT of the class. Alternatively, a custom method can
1015be added to an object declaration in a QML document with the following syntax:
1016
1017\code
1018 function <functionName>([<parameterName>[: <parameterType>][, ...]]) [: <returnType>] { <body> }
1019\endcode
1020
1021Methods can be added to a QML type in order to define standalone, reusable
1022blocks of JavaScript code. These methods can be invoked either internally or
1023by external objects.
1024
1025Unlike signals, method parameter types do not have to be declared as they
1026default to the \c var type. You should, however, declare them in order to
1027help qmlcachegen generate more performant code, and to improve maintainability.
1028
1029Attempting to declare two methods or signals with the same name in the same
1030type block is an error. However, a new method may reuse the name of an existing
1031method on the type. (This should be done with caution, as the existing method
1032may be hidden and become inaccessible.)
1033
1034Below is a \l Rectangle with a \c calculateHeight() method that is called when
1035assigning the \c height value:
1036
1037\qml
1038import QtQuick
1039Rectangle {
1040 id: rect
1041
1042 function calculateHeight(): real {
1043 return rect.width / 2;
1044 }
1045
1046 width: 100
1047 height: calculateHeight()
1048}
1049\endqml
1050
1051If the method has parameters, they are accessible by name within the method.
1052Below, when the \l MouseArea is clicked it invokes the \c moveTo() method which
1053can then refer to the received \c newX and \c newY parameters to reposition the
1054text:
1055
1056\qml
1057import QtQuick
1058
1059Item {
1060 width: 200; height: 200
1061
1062 MouseArea {
1063 anchors.fill: parent
1064 onClicked: mouse => label.moveTo(mouse.x, mouse.y)
1065 }
1066
1067 Text {
1068 id: label
1069
1070 function moveTo(newX: real, newY: real) {
1071 label.x = newX;
1072 label.y = newY;
1073 }
1074
1075 text: "Move me!"
1076 }
1077}
1078\endqml
1079
1080
1081\section2 Attached Properties and Attached Signal Handlers
1082
1083\e {Attached properties} and \e {attached signal handlers} are mechanisms that
1084enable objects to be annotated with extra properties or signal handlers that
1085are otherwise unavailable to the object. In particular, they allow objects to
1086access properties or signals that are specifically relevant to the individual
1087object.
1088
1089A QML type implementation may choose to \l {Providing Attached Properties}{create an \e {attaching
1090type} in C++} with particular properties and signals. Instances of this type can then be created and
1091\e attached to specific objects at run time, allowing those objects to access the properties and
1092signals of the attaching type. These are accessed by prefixing the properties and respective signal
1093handlers with the name of the attaching type.
1094
1095References to attached properties and handlers take the following syntax form:
1096
1097\code
1098<AttachingType>.<propertyName>
1099<AttachingType>.on<SignalName>
1100\endcode
1101
1102For example, the \l ListView type has an attached property
1103\l {ListView::isCurrentItem}{ListView.isCurrentItem} that is available to each delegate object in a
1104ListView. This can be used by each individual delegate object to determine
1105whether it is the currently selected item in the view:
1106
1107\qml
1108import QtQuick
1109
1110ListView {
1111 width: 240; height: 320
1112 model: 3
1113 delegate: Rectangle {
1114 width: 100; height: 30
1115 color: ListView.isCurrentItem ? "red" : "yellow"
1116 }
1117}
1118\endqml
1119
1120In this case, the name of the \e {attaching type} is \c ListView and the
1121property in question is \c isCurrentItem, hence the attached property is
1122referred to as \c ListView.isCurrentItem.
1123
1124An attached signal handler is referred to in the same way. For example, the
1125\l{Component::completed}{Component.onCompleted} attached signal handler is
1126commonly used to execute some JavaScript code when a component's creation
1127process has been completed. In the example below, once the \l ListModel has
1128been fully created, its \c Component.onCompleted signal handler will
1129automatically be invoked to populate the model:
1130
1131\qml
1132import QtQuick
1133
1134ListView {
1135 width: 240; height: 320
1136 model: ListModel {
1137 id: listModel
1138 Component.onCompleted: {
1139 for (let i = 0; i < 10; i++) {
1140 append({ Name: `Item ${i}` })
1141 }
1142 }
1143 }
1144 delegate: Text { text: index }
1145}
1146\endqml
1147
1148Since the name of the \e {attaching type} is \c Component and that type has a
1149\l{Component::completed}{completed} signal, the attached signal handler is
1150referred to as \c Component.onCompleted.
1151
1152
1153\section3 A Note About Accessing Attached Properties and Signal Handlers
1154
1155A common error is to assume that attached properties and signal handlers are
1156directly accessible from the children of the object to which these attributes
1157have been attached. This is not the case. The instance of the
1158\e {attaching type} is only attached to specific objects, not to the object
1159and all of its children.
1160
1161For example, below is a modified version of the earlier example involving
1162attached properties. This time, the delegate is an \l Item and the colored
1163\l Rectangle is a child of that item:
1164
1165\qml
1166import QtQuick
1167
1168ListView {
1169 width: 240; height: 320
1170 model: 3
1171 delegate: Item {
1172 width: 100; height: 30
1173
1174 Rectangle {
1175 width: 100; height: 30
1176 color: ListView.isCurrentItem ? "red" : "yellow" // WRONG! This won't work.
1177 }
1178 }
1179}
1180\endqml
1181
1182This does not work as expected because \c ListView.isCurrentItem is attached
1183\e only to the root delegate object, and not its children. Since the
1184\l Rectangle is a child of the delegate, rather than being the delegate itself,
1185it cannot access the \c isCurrentItem attached property as
1186\c ListView.isCurrentItem. So instead, the rectangle should access
1187\c isCurrentItem through the root delegate:
1188
1189\qml
1190ListView {
1191 delegate: Item {
1192 id: delegateItem
1193 width: 100; height: 30
1194
1195 Rectangle {
1196 width: 100; height: 30
1197 color: delegateItem.ListView.isCurrentItem ? "red" : "yellow" // correct
1198 }
1199 }
1200}
1201\endqml
1202
1203Now \c delegateItem.ListView.isCurrentItem correctly refers to the
1204\c isCurrentItem attached property of the delegate.
1205
1206\section2 Enumeration Attributes
1207
1208Enumerations provide a fixed set of named choices. They can be declared in QML using the \c enum keyword:
1209
1210\qml
1211// MyText.qml
1212Text {
1213 enum TextType {
1214 Normal,
1215 Heading
1216 }
1217}
1218\endqml
1219
1220As shown above, enumeration types (e.g. \c TextType) and values (e.g. \c Normal) must begin with an uppercase letter.
1221
1222Values are referred to via \c {<Type>.<EnumerationType>.<Value>} or \c {<Type>.<Value>}.
1223
1224\qml
1225// MyText.qml
1226Text {
1227 enum TextType {
1228 Normal,
1229 Heading
1230 }
1231
1232 property int textType: MyText.TextType.Normal
1233
1234 font.bold: textType === MyText.TextType.Heading
1235 font.pixelSize: textType === MyText.TextType.Heading ? 24 : 12
1236}
1237\endqml
1238
1239More information on enumeration usage in QML can be found in the documentation on
1240\l {QML Enumerations}.
1241
1242The ability to declare enumerations in QML was introduced in Qt 5.10.
1243
1244*/