1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
6 ** This file is part of the documentation of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:FDL$
9 ** GNU Free Documentation License
10 ** Alternatively, this file may be used under the terms of the GNU Free
11 ** Documentation License version 1.3 as published by the Free Software
12 ** Foundation and appearing in the file included in the packaging of
16 ** Alternatively, this file may be used in accordance with the terms
17 ** and conditions contained in a signed written agreement between you
26 ****************************************************************************/
29 \page qtqml-syntax-objectattributes.html
30 \title QML Object Attributes
31 \brief Description of QML object type attributes
33 Every QML object type has a defined set of attributes. Each instance of an
34 object type is created with the set of attributes that have been defined for
35 that object type. There are several different kinds of attributes which
36 can be specified, which are described below.
38 \section1 Attributes in Object Declarations
40 An \l{qtqml-syntax-basics.html#object-declarations}{object declaration} in a
41 QML document defines a new type. It also declares an object hierarchy that
42 will be instantiated should an instance of that newly defined type be created.
44 The set of QML object-type attribute types is as follows:
47 \li the \e id attribute
48 \li property attributes
50 \li signal handler attributes
52 \li attached properties and attached signal handler attributes
55 These attributes are discussed in detail below.
57 \section2 The \e id Attribute
59 Every QML object type has exactly one \e id attribute. This attribute is
60 provided by the language itself, and cannot be redefined or overridden by any
63 A value may be assigned to the \e id attribute of an object instance to allow
64 that object to be identified and referred to by other objects. This \c id must
65 begin with a lower-case letter or an underscore, and cannot contain characters
66 other than letters, numbers and underscores.
68 Below is a \l TextInput object and a \l Text object. The \l TextInput object's
69 \c id value is set to "myTextInput". The \l Text object sets its \c text
70 property to have the same value as the \c text property of the \l TextInput,
71 by referring to \c myTextInput.text. Now, both items will display the same
78 width: 200; height: 200
80 TextInput { id: myTextInput; text: "Hello World" }
82 Text { text: myTextInput.text }
86 An object can be referred to by its \c id from anywhere within the
87 \e {component scope} in which it is declared. Therefore, an \c id value must
88 always be unique within its component scope. See
89 \l{qtqml-documents-scope.html}{Scope and Naming Resolution} for more
92 Once an object instance is created, the value of its \e id attribute cannot
93 be changed. While it may look like an ordinary property, the \c id attribute
94 is \bold{not} an ordinary \c property attribute, and special semantics apply
95 to it; for example, it is not possible to access \c myTextInput.id in the above
99 \section2 Property Attributes
101 A property is an attribute of an object that can be assigned a static value
102 or bound to a dynamic expression. A property's value can be read by other
103 objects. Generally it can also be modified by another object, unless a
104 particular QML type has explicitly disallowed this for a specific property.
106 \section3 Defining Property Attributes
108 A property may be defined for a type in C++ by registering a
109 Q_PROPERTY of a class which is then registered with the QML type system.
110 Alternatively, a custom property of an object type may be defined in
111 an object declaration in a QML document with the following syntax:
114 [default] property <propertyType> <propertyName>
117 In this way an object declaration may \l {Defining Object Types from QML}
118 {expose a particular value} to outside objects or maintain some internal
121 Property names must begin with a lower case letter and can only contain
122 letters, numbers and underscores. \l {JavaScript Reserved Words}
123 {JavaScript reserved words} are not valid property names. The \c default
124 keyword is optional, and modifies the semantics of the property being declared.
125 See the upcoming section on \l {Default Properties}{default properties} for
126 more information about the \c default property modifier.
128 Declaring a custom property implicitly creates a value-change
129 \l{Signal attributes}{signal} for that property, as well as an associated
130 \l{Signal handler attributes}{signal handler} called
131 \e on<PropertyName>Changed, where \e <PropertyName> is the name of the
132 property, with the first letter capitalized.
134 For example, the following object declaration defines a new type which
135 derives from the Rectangle base type. It has two new properties,
136 with a \l{Signal handler attributes}{signal handler} implemented for one of
137 those new properties:
141 property color previousColor
142 property color nextColor
143 onNextColorChanged: console.log("The next color will be: " + nextColor.toString())
147 \section4 Valid Types in Custom Property Definitions
149 The following types can be used as custom property types:
154 \li \l real, \l double
159 The \l var type is a generic placeholder type that can hold any type of value,
160 including lists and objects:
163 property var someNumber: 1.5
164 property var someString: "abc"
165 property var someBool: true
166 property var someList: [1, 2, "three", "four"]
167 property var someObject: Rectangle { width: 100; height: 100; color: "red" }
170 For convenience, the following types can also be used as custom property types.
171 Using these types specifically instead of the \l var type provides type safety
172 and may also assist with application optimization:
189 \note Some of the above types are only available if the Qt Quick module has
190 been imported by the application.
192 Additionally, any \l{QML Object Types}{QML object type} can be used as a
193 property type. For example:
196 property Item someItem
197 property Rectangle someRectangle
200 This applies to \l {Defining Object Types from QML}{custom QML types} as well.
201 If a QML type was defined in a file named \c ColorfulButton.qml (in a directory
202 which was then imported by the client), then a property of type
203 \c ColorfulButton would also be valid.
206 \section3 Values of Property Attributes
208 The value of a property of an object instance may specified in an
209 object declaration in two separate ways:
211 \li a value assignment on initialization
212 \li an imperative value assignment
215 The value in either case may be either a binding expression or a static value.
217 \section4 Value Assignment on Initialization
219 The syntax for assigning a value to a property on initialization is:
222 <propertyName> : <value>
225 An initialization value assignment may be combined with a property definition
226 in an object declaration, if desired. In that case, the syntax of the property
230 [default] property <propertyType> <propertyName> : <value>
233 An example of property value initialization follows:
240 property color nextColor: "blue" // combined property declaration and initialization
244 \section4 Imperative Value Assignment
246 An imperative value assignment is where a property value (either static value
247 or binding expression) is assigned to a property from imperative JavaScript
248 code. The syntax of an imperative value assignment is just the JavaScript
249 assignment operator, as shown below:
252 [<objectId>.]<propertyName> = value
255 An example of imperative value assignment follows:
262 Component.onCompleted: {
268 \section4 Valid Property Values
270 As previously noted, there are two kinds of values which may be assigned to a
271 property: static values, and binding expression values.
280 \li A value whose type matches (or can be converted to) that of
281 the property may be assigned to the property.
284 \li Binding Expression
285 \li A JavaScript expression which may be evaluated, whose result is a
286 value whose type matches (or can be converted to) that of the
287 property may be assigned to the property. The expression will be
288 automatically re-evaluated (and the new result assigned to the
289 property) by the QML engine should the value of any properties accessed
290 during evaluation change.
293 An example of these two types of values being assigned to properties follows:
299 // both of these are static value assignments on initialization
304 // both of these are binding expression value assignments on initialization
305 width: parent.width / 2
306 height: parent.height
311 In many cases, a string value may be converted automatically to a
312 different type of value, as QML provides string converters for many property
313 types (thus you can assign the string \c "red" to a color property).
315 It is important to note that in order to assign a binding expression to a
316 property in an imperative value assignment, the right-hand-side of
317 the assignment (the binding expression) must be a function returned by the
318 \l{Qt::binding()}{Qt.binding()} function, which returns a value of the
319 appropriate type. A binding expression value may be assigned to a property
320 via an initialization value assignment without using that function (and, in
321 fact, attempting to do so will result in an error). See the documentation
322 about \l{qtqml-syntax-propertybinding.html}{property binding} for more
323 information on the topic.
326 \section3 Type Safety
328 Properties are type safe. A property can only be assigned a value that matches
331 For example, if a property is a real, and if you try to assign a string to it,
332 you will get an error:
335 property int volume: "four" // generates an error; the property's object will not be loaded
338 Likewise if a property is assigned a value of the wrong type during run time,
339 the new value will not be assigned, and an error will be generated.
341 As noted in a previous section, some property types do not have a natural
342 value representation, and for those property types the QML engine
343 automatically performs string-to-typed-value conversion. So, for example,
344 even though properties of the \c color type store colors and not strings,
345 you are able to assign the string \c "red" to a color property, without an
346 error being reported.
348 See \l {QML Basic Types} for a list of the types of properties that are
349 supported by default. Additionally, any available \l {QML Object Types}
350 {QML object type} may also be used as a property type.
352 \section3 Special Property Types
354 \section4 Object List Property Attributes
356 A \l list type property can be assigned a list of QML object-type values.
357 The syntax for defining an object list value is a comma-separated list
358 surrounded by square brackets:
361 [ <item 1>, <item 2>, ... ]
364 For example, the \l Item type has a \l {Item::states}{states} property that is
365 used to hold a list of \l State type objects. The code below initializes the
366 value of this property to a list of three \l State objects:
373 State { name: "loading" },
374 State { name: "running" },
375 State { name: "stopped" }
380 If the list contains a single item, the square brackets may be omitted:
386 states: State { name: "running" }
390 A \l list type property may be specified in an object declaration with the
394 [default] property list<<objectType>> propertyName
397 and, like other property declarations, a property initialization may be
398 combined with the property declaration with the following syntax:
401 [default] property list<<objectType>> propertyName: <value>
404 An example of list property declaration follows:
410 // declaration without initialization
411 property list<Rectangle> siblingRects
413 // declaration with initialization
414 property list<Rectangle> childRects: [
415 Rectangle { color: "red" },
416 Rectangle { color: "blue"}
421 If you wish to declare a property to store a list of values which are not
422 necessarily QML object-type values, you should declare a \l var property
426 \section4 Grouped Properties
428 In some cases properties contain a logical group of sub-property attributes.
429 These sub-property attributes can be assigned to using either the dot notation
432 For example, the \l Text type has a \l{Text::font}{font} group property. Below,
433 the first \l Text object initializes its \c font values using dot notation,
434 while the second uses group notation:
445 font { pixelSize: 12; bold: true }
449 Grouped property types are basic types which have subproperties. Some of these
450 basic types are provided by the QML language, while others may only be used if
451 the Qt Quick module is imported. See the documentation about
452 \l{QML Basic Types} for more information.
455 \section3 Property Aliases
457 Property aliases are properties which hold a reference to another property.
458 Unlike an ordinary property definition, which allocates a new, unique storage
459 space for the property, a property alias connects the newly declared property
460 (called the aliasing property) as a direct reference to an existing property
461 (the aliased property).
463 A property alias declaration looks like an ordinary property definition, except
464 that it requires the \c alias keyword instead of a property type, and the
465 right-hand-side of the property declaration must be a valid alias reference:
468 [default] property alias <name>: <alias reference>
471 Unlike an ordinary property, an alias can only refer to a object, or the
472 property of a object, that is within the scope of the \l{QML Object Types}
473 {type} within which the alias is declared. It cannot contain arbitrary
474 JavaScript expressions and it cannot refer to objects declared outside of
475 the scope of its type. Also note the \e {alias reference} is not optional,
476 unlike the optional default value for an ordinary property; the alias reference
477 must be provided when the alias is first declared.
479 For example, below is a \c Button type with a \c buttonText aliased property
480 which is connected to the \c text object of the \l Text child:
487 property alias buttonText: textItem.text
489 width: 100; height: 30; color: "yellow"
491 Text { id: textItem }
495 The following code would create a \c Button with a defined text string for the
496 child \l Text object:
499 Button { buttonText: "Click Me" }
502 Here, modifying \c buttonText directly modifies the textItem.text value; it
503 does not change some other value that then updates textItem.text. If
504 \c buttonText was not an alias, changing its value would not actually change
505 the displayed text at all, as property bindings are not bi-directional: the
506 \c buttonText value would have changed if textItem.text was changed, but not
507 the other way around.
510 \section4 Considerations for Property Aliases
512 Aliases are only activated once a component has been fully initialized. An
513 error is generated when an uninitialized alias is referenced. Likewise,
514 aliasing an aliasing property will also result in an error.
516 \snippet qml/properties.qml alias complete
518 When importing a \l{QML Object Types}QML object type} with a property alias in
519 the root object, however, the property appear as a regular Qt property and
520 consequently can be used in alias references.
522 It is possible for an aliasing property to have the same name as an existing
523 property, effectively overwriting the existing property. For example,
524 the following QML type has a \c color alias property, named the same as the
525 built-in \l {Rectangle::color} property:
527 \snippet qml/properties.qml alias overwrite
529 Any object that use this type and refer to its \c color property will be
530 referring to the alias rather than the ordinary \l {Rectangle::color} property.
531 Internally, however, the red can correctly set its \c color
532 property and refer to the actual defined property rather than the alias.
535 \section3 Default Properties
537 An object definition can have a single \e default property. A default property
538 is the property to which a value is assigned if an object is declared within
539 another object's definition without attaching it as a value to a particular
542 Declaring a property with the optional \c default keyword marks it as the
543 default property. For example, say there is a file MyLabel.qml with a default
544 property \c someText:
551 default property var someText
553 text: "Hello, " + someText.text
557 The \c someText value could be assigned to in a \c MyLabel object definition,
562 Text { text: "world!" }
566 This has exactly the same effect as the following:
570 someText: Text { text: "world!" }
574 However, since the \c someText property has been marked as the default
575 property, it is not necessary to explicitly assign the \l Text object
578 You will notice that child objects can be added to any \l {Item}-based type
579 without explicitly adding them to the \l {Item::children}{children} property.
580 This is because the default property of \l Item is its \c data property, and
581 any items added to this list for an \l Item are automatically added to its
582 list of \l {Item::children}{children}.
584 Default properties can be useful for reassigning the children of an item. See
585 the \l{declarative/ui-components/tabwidget}{TabWidget example}, which uses a
586 default property to automatically reassign children of the TabWidget as
587 children of an inner ListView.
590 \section2 Signal Attributes
592 A signal is a notification from an object that some event has occurred: for
593 example, a property has changed, an animation has started or stopped, or
594 when an image has been downloaded. The \l MouseArea type, for example, has
595 a \l {MouseArea::clicked}{clicked} signal that is emitted when the user clicks
596 within the mouse area.
598 An object can be notified through a \l{Signal handler attributes}
599 {signal handler} whenever it a particular signal is emitted. A signal handler
600 is declared with the syntax \e on<Signal> where \e <Signal> is the name of the
601 signal, with the first letter capitalized. The signal handler must be declared
602 within the definition of the object that emits the signal, and the handler
603 should contain the block of JavaScript code to be executed when the signal
606 For example, the \e onClicked signal handler below is declared within the
607 \l MouseArea object definition, and is invoked when the \l MouseArea is
608 clicked, causing a console message to be printed:
614 width: 100; height: 100
619 console.log("Click!")
625 \section3 Defining Signal Attributes
627 A signal may be defined for a type in C++ by registering a Q_SIGNAL of a class
628 which is then registered with the QML type system. Alternatively, a custom
629 signal for an object type may be defined in an object declaration in a QML
630 document with the following syntax:
633 signal <signalName>[([<type> <parameter name>[, ...]])]
636 Attempting to declare two signals or methods with the same name in the same
637 type block is an error. However, a new signal may reuse the name of an existing
638 signal on the type. (This should be done with caution, as the existing signal
639 may be hidden and become inaccessible.)
641 Here are three examples of signal declarations:
649 signal actionPerformed(string action, var actionResult)
653 If the signal has no parameters, the "()" brackets are optional. If parameters
654 are used, the parameter types must be declared, as for the \c string and \c var
655 arguments for the \c actionPerformed signal above. The allowed parameter types
656 are the same as those listed under \l {custom property types} on this page.
658 To emit a signal, invoke it as a method. Any relevant
659 \l{Signal handler attributes}{signal handlers} will be invoked when the signal
660 is emitted, and handlers can use the defined signal argument names to access
661 the respective arguments.
663 \section3 Property Change Signals
665 QML types also provide built-in \e {property change signals} that are emitted
666 whenever a property value changes, as previously described in the section on
667 \l{Property attributes}{property attributes}. See the upcoming section on
668 \l{Property change signal handlers}{property change signal handlers} for more
669 information about why these signals are useful, and how to use them.
672 \section2 Signal Handler Attributes
674 Signal handlers are a special sort of \l{Method attributes}{method attribute},
675 where the method implementation is invoked by the QML engine whenever the
676 associated signal is emitted. Adding a signal to an object definition in QML
677 will automatically add an associated signal handler to the object definition,
678 which has, by default, an empty implementation. Clients can provide an
679 implementation, to implement program logic.
681 Consider the following \c SquareButton type, whose definition is provided in
682 the \c SquareButton.qml file as shown below, with signals \c activated and
690 signal activated(real xPosition, real yPosition)
693 width: 100; height: 100
697 onPressed: root.activated(mouse.x, mouse.y)
698 onRelased: root.deactivated()
703 These signals could be received by any \c SquareButton objects in another QML
704 file in the same directory, where implementations for the signal handlers are
705 provided by the client:
710 onActivated: console.log("Activated at " + xPosition + "," + yPosition)
711 onDeactivated: console.log("Deactivated!")
715 See the \l {Signal and Handler Event System} for more details on use of
718 \section3 Property Change Signal Handlers
720 Signal handlers for property change signal take the syntax form
721 \e on<Property>Changed where \e <Property> is the name of the property,
722 with the first letter capitalized. For example, although the \l TextInput type
723 documentation does not document a \c textChanged signal, this signal is
724 implicitly available through the fact that \l TextInput has a
725 \l {TextInput::text}{text} property and so it is possible to write an
726 \c onTextChanged signal handler to be called whenever this property changes:
734 onTextChanged: console.log("Text has changed to:", text)
739 \section2 Method Attributes
741 A method of an object type is a function which may be called to perform some
742 processing or trigger further events. A method can be connected to a signal so
743 that it is automatically invoked whenever the signal is emitted. See
744 \l {Signal and Handler Event System} for more details.
746 \section3 Defining Method Attributes
748 A method may be defined for a type in C++ by tagging a function of a class
749 which is then registered with the QML type system with Q_INVOKABLE or by
750 registering it as a Q_SLOT of the class. Alternatively, a custom method can
751 be added to an object declaration in a QML document with the following syntax:
754 function <functionName>([<parameterName>[, ...]]) { <body> }
757 Methods can be added to a QML type in order to define standalone, reusable
758 blocks of JavaScript code. These methods can be invoked either internally or
761 Unlike signals, method parameter types do not have to be declared as they
762 default to the \c var type.
764 Attempting to declare two methods or signals with the same name in the same
765 type block is an error. However, a new method may reuse the name of an existing
766 method on the type. (This should be done with caution, as the existing method
767 may be hidden and become inaccessible.)
769 Below is a \l Rectangle with a \c calculateHeight() method that is called when
770 assigning the \c height value:
777 function calculateHeight() {
778 return rect.width / 2;
782 height: calculateHeight()
786 If the method has parameters, they are accessible by name within the method.
787 Below, when the \l MouseArea is clicked it invokes the \c moveTo() method which
788 can then refer to the received \c newX and \c newY parameters to reposition the
795 width: 200; height: 200
799 onClicked: label.moveTo(mouse.x, mouse.y)
805 function moveTo(newX, newY) {
816 \section2 Attached Properties and Attached Signal Handlers
818 \e {Attached properties} and \e {attached signal handlers} are mechanisms that
819 enable objects to be annotated with extra properties or signal handlers that
820 are otherwise unavailable to the object. In particular, they allow objects to
821 access properties or signals that are specifically relevant to the individual
824 A QML type implementation may choose to create an \e {attaching type} with
825 particular properties and signals. Instances of this type can then be created
826 and \e attached to specific objects at run time, allowing those objects to
827 access the properties and signals of the attaching type. These are accessed by
828 prefixing the properties and respective signal handlers with the name of the
831 For example, the \l ListView type has an attached property
832 \l ListView.isCurrentItem that is available to each delegate object in a
833 ListView. This can be used by each individual delegate object to determine
834 whether it is the currently selected item in the view:
840 width: 240; height: 320
842 delegate: Rectangle {
843 width: 100; height: 30
844 color: ListView.isCurrentItem ? "red" : "yellow"
849 In this case, the name of the \e {attaching type} is \c ListView and the
850 property in question is \c isCurrentItem, hence the attached property is
851 referred to as \c ListView.isCurrentItem.
853 An attached signal handler is referred to in the same way. For example, the
854 \c Component.isCompleted attached signal handler is commonly used to execute
855 some JavaScript code when a component's creation process has been completed.
856 In the example below, once the \l ListModel has been fully created, its
857 \c Component.onCompleted signal handler will automatically be invoked to
864 width: 240; height: 320
867 Component.onCompleted: {
868 for (var i=0; i<10; i++)
869 listModel.append({"Name": "Item " + i})
872 delegate: Text { text: index }
876 Since the name of the \e {attaching type} is \c Component and that type has a
877 \c completed signal, the attached signal handler is referred to as
878 \c Component.isCompleted.
881 \section3 A Note About Accessing Attached Properties and Signal Handlers
883 A common error is to assume that attached properties and signal handlers are
884 directly accessible from the children of the object to which these attributes
885 have been attached. This is not the case. The instance of the
886 \e {attaching type} is only attached to specific objects, not to the object
887 and all of its children.
889 For example, below is a modified version of the earlier example involving
890 attached properties. This time, the delegate is an \l Item and the colored
891 \l Rectangle is a child of that item:
897 width: 240; height: 320
900 width: 100; height: 30
903 width: 100; height: 30
904 color: ListView.isCurrentItem ? "red" : "yellow" // WRONG! This won't work.
910 This does not work as expected because \c ListView.isCurrentItem is attached
911 \e only to the root delegate object, and not its children. Since the
912 \l Rectangle is a child of the delegate, rather than being the delegate itself,
913 it cannot access the \c isCurrentItem attached property as
914 \c ListView.isCurrentItem. So instead, the rectangle should access
915 \c isCurrentItem through the root delegate:
922 width: 100; height: 30
925 width: 100; height: 30
926 color: delegateItem.ListView.isCurrentItem ? "red" : "yellow" // correct
932 Now \c delegateItem.ListView.isCurrentItem correctly refers to the
933 \c isCurrentItem attached property of the delegate.