Change copyrights from Nokia to Digia
[profile/ivi/qtdeclarative.git] / src / qml / doc / src / syntax / objectattributes.qdoc
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/legal
5 **
6 ** This file is part of the documentation of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:FDL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and Digia.  For licensing terms and
14 ** conditions see http://qt.digia.com/licensing.  For further information
15 ** use the contact form at http://qt.digia.com/contact-us.
16 **
17 ** GNU Free Documentation License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Free
19 ** Documentation License version 1.3 as published by the Free Software
20 ** Foundation and appearing in the file included in the packaging of
21 ** this file.  Please review the following information to ensure
22 ** the GNU Free Documentation License version 1.3 requirements
23 ** will be met: http://www.gnu.org/copyleft/fdl.html.
24 ** $QT_END_LICENSE$
25 **
26 ****************************************************************************/
27
28 /*!
29 \page qtqml-syntax-objectattributes.html
30 \title QML Object Attributes
31 \brief Description of QML object type attributes
32
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.
37
38 \section1 Attributes in Object Declarations
39
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.
43
44 The set of QML object-type attribute types is as follows:
45
46 \list
47 \li the \e id attribute
48 \li property attributes
49 \li signal attributes
50 \li signal handler attributes
51 \li method attributes
52 \li attached properties and attached signal handler attributes
53 \endlist
54
55 These attributes are discussed in detail below.
56
57 \section2 The \e id Attribute
58
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
61 QML object type.
62
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.
67
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
72 text:
73
74 \qml
75 import QtQuick 2.0
76
77 Column {
78     width: 200; height: 200
79
80     TextInput { id: myTextInput; text: "Hello World" }
81
82     Text { text: myTextInput.text }
83 }
84 \endqml
85
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
90 information.
91
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 \b{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
96 example.
97
98
99 \section2 Property Attributes
100
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.
105
106 \section3 Defining Property Attributes
107
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:
112
113 \code
114     [default] property <propertyType> <propertyName>
115 \endcode
116
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
119 state more easily.
120
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.
127
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.
133
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:
138
139 \qml
140 Rectangle {
141     property color previousColor
142     property color nextColor
143     onNextColorChanged: console.log("The next color will be: " + nextColor.toString())
144 }
145 \endqml
146
147 \section4 Valid Types in Custom Property Definitions
148
149 Any of the \l {QML Basic Types} aside from the \l enumeration type can be used
150 as custom property types. For example, these are all valid property declarations:
151
152 \qml
153 Item {
154     property int someNumber
155     property string someString
156     property url someUrl
157 }
158 \endqml
159
160 (Enumeration values are simply whole number values and can be referred to with
161 the \l int type instead.)
162
163 Some basic types are provided by the \c QtQuick module and thus cannot be used
164 as property types unless the module is imported. See the \l {QML Basic Types}
165 documentation for more details.
166
167 Note the \l var basic type is a generic placeholder type that can hold any
168 type of value, including lists and objects:
169
170 \code
171 property var someNumber: 1.5
172 property var someString: "abc"
173 property var someBool: true
174 property var someList: [1, 2, "three", "four"]
175 property var someObject: Rectangle { width: 100; height: 100; color: "red" }
176 \endcode
177
178 Additionally, any \l{QML Object Types}{QML object type} can be used as a
179 property type. For example:
180
181 \code
182 property Item someItem
183 property Rectangle someRectangle
184 \endcode
185
186 This applies to \l {Defining Object Types from QML}{custom QML types} as well.
187 If a QML type was defined in a file named \c ColorfulButton.qml (in a directory
188 which was then imported by the client), then a property of type
189 \c ColorfulButton would also be valid.
190
191
192 \section3 Values of Property Attributes
193
194 The value of a property of an object instance may specified in an
195 object declaration in two separate ways:
196 \list
197   \li a value assignment on initialization
198   \li an imperative value assignment
199 \endlist
200
201 The value in either case may be either a binding expression or a static value.
202
203 \section4 Value Assignment on Initialization
204
205 The syntax for assigning a value to a property on initialization is:
206
207 \code
208     <propertyName> : <value>
209 \endcode
210
211 An initialization value assignment may be combined with a property definition
212 in an object declaration, if desired.  In that case, the syntax of the property
213 definition becomes:
214
215 \code
216     [default] property <propertyType> <propertyName> : <value>
217 \endcode
218
219 An example of property value initialization follows:
220
221 \qml
222 import QtQuick 2.0
223
224 Rectangle {
225     color: "red"
226     property color nextColor: "blue" // combined property declaration and initialization
227 }
228 \endqml
229
230 \section4 Imperative Value Assignment
231
232 An imperative value assignment is where a property value (either static value
233 or binding expression) is assigned to a property from imperative JavaScript
234 code.  The syntax of an imperative value assignment is just the JavaScript
235 assignment operator, as shown below:
236
237 \code
238     [<objectId>.]<propertyName> = value
239 \endcode
240
241 An example of imperative value assignment follows:
242
243 \qml
244 import QtQuick 2.0
245
246 Rectangle {
247     id: rect
248     Component.onCompleted: {
249         rect.color = "red"
250     }
251 }
252 \endqml
253
254 \section4 Valid Property Values
255
256 As previously noted, there are two kinds of values which may be assigned to a
257 property: static values, and binding expression values.
258
259 \table
260     \header
261     \li Kind
262     \li Semantics
263
264     \row
265     \li Static Value
266     \li A value whose type matches (or can be converted to) that of
267         the property may be assigned to the property.
268
269     \row
270     \li Binding Expression
271     \li A JavaScript expression which may be evaluated, whose result is a
272         value whose type matches (or can be converted to) that of the
273         property may be assigned to the property.  The expression will be
274         automatically re-evaluated (and the new result assigned to the
275         property) by the QML engine should the value of any properties accessed
276         during evaluation change.
277 \endtable
278
279 An example of these two types of values being assigned to properties follows:
280
281 \qml
282 import QtQuick 2.0
283
284 Rectangle {
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 In many cases, a string value may be converted automatically to a
298 different type of value, as QML provides string converters for many property
299 types (thus you can assign the string \c "red" to a color property).
300
301 It is important to note that in order to assign a binding expression to a
302 property in an imperative value assignment, the right-hand-side of
303 the assignment (the binding expression) must be a function returned by the
304 \l{Qt::binding()}{Qt.binding()} function, which returns a value of the
305 appropriate type.  A binding expression value may be assigned to a property
306 via an initialization value assignment without using that function (and, in
307 fact, attempting to do so will result in an error).  See the documentation
308 about \l{qtqml-syntax-propertybinding.html}{property binding} for more
309 information on the topic.
310
311
312 \section3 Type Safety
313
314 Properties are type safe. A property can only be assigned a value that matches
315 the property type.
316
317 For example, if a property is a real, and if you try to assign a string to it,
318 you will get an error:
319
320 \code
321 property int volume: "four"  // generates an error; the property's object will not be loaded
322 \endcode
323
324 Likewise if a property is assigned a value of the wrong type during run time,
325 the new value will not be assigned, and an error will be generated.
326
327 As noted in a previous section, some property types do not have a natural
328 value representation, and for those property types the QML engine
329 automatically performs string-to-typed-value conversion.  So, for example,
330 even though properties of the \c color type store colors and not strings,
331 you are able to assign the string \c "red" to a color property, without an
332 error being reported.
333
334 See \l {QML Basic Types} for a list of the types of properties that are
335 supported by default.  Additionally, any available \l {QML Object Types}
336 {QML object type} may also be used as a property type.
337
338 \section3 Special Property Types
339
340 \section4 Object List Property Attributes
341
342 A \l list type property can be assigned a list of QML object-type values.
343 The syntax for defining an object list value is a comma-separated list
344 surrounded by square brackets:
345
346 \code
347     [ <item 1>, <item 2>, ... ]
348 \endcode
349
350 For example, the \l Item type has a \l {Item::states}{states} property that is
351 used to hold a list of \l State type objects. The code below initializes the
352 value of this property to a list of three \l State objects:
353
354 \qml
355 import QtQuick 2.0
356
357 Item {
358     states: [
359         State { name: "loading" },
360         State { name: "running" },
361         State { name: "stopped" }
362     ]
363 }
364 \endqml
365
366 If the list contains a single item, the square brackets may be omitted:
367
368 \qml
369 import QtQuick 2.0
370
371 Item {
372     states: State { name: "running" }
373 }
374 \endqml
375
376 A \l list type property may be specified in an object declaration with the
377 following syntax:
378
379 \code
380     [default] property list<<objectType>> propertyName
381 \endcode
382
383 and, like other property declarations, a property initialization may be
384 combined with the property declaration with the following syntax:
385
386 \code
387     [default] property list<<objectType>> propertyName: <value>
388 \endcode
389
390 An example of list property declaration follows:
391
392 \qml
393 import QtQuick 2.0
394
395 Rectangle {
396     // declaration without initialization
397     property list<Rectangle> siblingRects
398
399     // declaration with initialization
400     property list<Rectangle> childRects: [
401         Rectangle { color: "red" },
402         Rectangle { color: "blue"}
403     ]
404 }
405 \endqml
406
407 If you wish to declare a property to store a list of values which are not
408 necessarily QML object-type values, you should declare a \l var property
409 instead.
410
411
412 \section4 Grouped Properties
413
414 In some cases properties contain a logical group of sub-property attributes.
415 These sub-property attributes can be assigned to using either the dot notation
416 or group notation.
417
418 For example, the \l Text type has a \l{Text::font.family}{font} group property. Below,
419 the first \l Text object initializes its \c font values using dot notation,
420 while the second uses group notation:
421
422 \code
423 Text {
424     //dot notation
425     font.pixelSize: 12
426     font.b: true
427 }
428
429 Text {
430     //group notation
431     font { pixelSize: 12; b: true }
432 }
433 \endcode
434
435 Grouped property types are basic types which have subproperties.  Some of these
436 basic types are provided by the QML language, while others may only be used if
437 the Qt Quick module is imported.  See the documentation about
438 \l{QML Basic Types} for more information.
439
440
441 \section3 Property Aliases
442
443 Property aliases are properties which hold a reference to another property.
444 Unlike an ordinary property definition, which allocates a new, unique storage
445 space for the property, a property alias connects the newly declared property
446 (called the aliasing property) as a direct reference to an existing property
447 (the aliased property).
448
449 A property alias declaration looks like an ordinary property definition, except
450 that it requires the \c alias keyword instead of a property type, and the
451 right-hand-side of the property declaration must be a valid alias reference:
452
453 \code
454 [default] property alias <name>: <alias reference>
455 \endcode
456
457 Unlike an ordinary property, an alias can only refer to a object, or the
458 property of a object, that is within the scope of the \l{QML Object Types}
459 {type} within which the alias is declared. It cannot contain arbitrary
460 JavaScript expressions and it cannot refer to objects declared outside of
461 the scope of its type. Also note the \e {alias reference} is not optional,
462 unlike the optional default value for an ordinary property; the alias reference
463 must be provided when the alias is first declared.
464
465 For example, below is a \c Button type with a \c buttonText aliased property
466 which is connected to the \c text object of the \l Text child:
467
468 \qml
469 // Button.qml
470 import QtQuick 2.0
471
472 Rectangle {
473     property alias buttonText: textItem.text
474
475     width: 100; height: 30; color: "yellow"
476
477     Text { id: textItem }
478 }
479 \endqml
480
481 The following code would create a \c Button with a defined text string for the
482 child \l Text object:
483
484 \qml
485 Button { buttonText: "Click Me" }
486 \endqml
487
488 Here, modifying \c buttonText directly modifies the textItem.text value; it
489 does not change some other value that then updates textItem.text. If
490 \c buttonText was not an alias, changing its value would not actually change
491 the displayed text at all, as property bindings are not bi-directional: the
492 \c buttonText value would have changed if textItem.text was changed, but not
493 the other way around.
494
495
496 \section4 Considerations for Property Aliases
497
498 Aliases are only activated once a component has been fully initialized. An
499 error is generated when an uninitialized alias is referenced. Likewise,
500 aliasing an aliasing property will also result in an error.
501
502 \snippet qml/properties.qml alias complete
503
504 When importing a \l{QML Object Types}{QML object type} with a property alias in
505 the root object, however, the property appear as a regular Qt property and
506 consequently can be used in alias references.
507
508 It is possible for an aliasing property to have the same name as an existing
509 property, effectively overwriting the existing property. For example,
510 the following QML type has a \c color alias property, named the same as the
511 built-in \l {Rectangle::color} property:
512
513 \snippet qml/properties.qml alias overwrite
514
515 Any object that use this type and refer to its \c color property will be
516 referring to the alias rather than the ordinary \l {Rectangle::color} property.
517 Internally, however, the red can correctly set its \c color
518 property and refer to the actual defined property rather than the alias.
519
520
521 \section3 Default Properties
522
523 An object definition can have a single \e default property. A default property
524 is the property to which a value is assigned if an object is declared within
525 another object's definition without declaring it as a value for a particular
526 property.
527
528 Declaring a property with the optional \c default keyword marks it as the
529 default property. For example, say there is a file MyLabel.qml with a default
530 property \c someText:
531
532 \qml
533 // MyLabel.qml
534 import QtQuick 2.0
535
536 Text {
537     default property var someText
538
539     text: "Hello, " + someText.text
540 }
541 \endqml
542
543 The \c someText value could be assigned to in a \c MyLabel object definition,
544 like this:
545
546 \qml
547 MyLabel {
548     Text { text: "world!" }
549 }
550 \endqml
551
552 This has exactly the same effect as the following:
553
554 \qml
555 MyLabel {
556     someText: Text { text: "world!" }
557 }
558 \endqml
559
560 However, since the \c someText property has been marked as the default
561 property, it is not necessary to explicitly assign the \l Text object
562 to this property.
563
564 You will notice that child objects can be added to any \l {Item}-based type
565 without explicitly adding them to the \l {Item::children}{children} property.
566 This is because the default property of \l Item is its \c data property, and
567 any items added to this list for an \l Item are automatically added to its
568 list of \l {Item::children}{children}.
569
570 Default properties can be useful for reassigning the children of an item. See
571 the  \l{declarative/ui-components/tabwidget}{TabWidget example}, which uses a
572 default property to automatically reassign children of the TabWidget as
573 children of an inner ListView.
574
575
576 \section3 Read-Only Properties
577
578 An object declaration may define a read-only property using the \c readonly
579 keyword, with the following syntax:
580
581 \code
582     readonly property <propertyType> <propertyName> : <initialValue>
583 \endcode
584
585 Read-only properties must be assigned a value on initialization. After a
586 read-only property is initialized, it no longer possible to give it a value,
587 whether from imperative code or otherwise.
588
589 For example, the code in the \c Component.onCompleted block below is invalid:
590
591 \qml
592 Item {
593     readonly property int someNumber: 10
594
595     Component.onCompleted: someNumber = 20  // doesn't work, causes an error
596 }
597 \endqml
598
599 \note A read-only property cannot also be a \l{Default Properties}{default} or
600 \l {Property Aliases}{alias} property.
601
602
603 \section3 Property Modifier Objects
604
605 Properties can have
606 \l{qtqml-cppintegration-definetypes.html#property-modifier-types}
607 {property value modifier objects} associated with them.
608 The syntax for declaring an instance of a property modifier type associated
609 with a particular property is as follows:
610
611 \code
612 <PropertyModifierTypeName> on <propertyName> {
613     // attributes of the object instance
614 }
615 \endcode
616
617 It is important to note that the above syntax is in fact an
618 \l{qtqml-syntax-basics.html#object-declarations}{object declaration} which
619 will instantiate an object which acts on a pre-existing property.
620
621 Certain property modifier types may only be applicable to specific property
622 types, however this is not enforced by the language.  For example, the
623 \c NumberAnimation type provided by \c QtQuick will only animate
624 numeric-type (such as \c int or \c real) properties.  Attempting to use a
625 \c NumberAnimation with non-numeric property will not result in an error,
626 however the non-numeric property will not be animated.  The behavior of a
627 property modifier type when associated with a particular property type is
628 defined by its implementation.
629
630
631 \section2 Signal Attributes
632
633 A signal is a notification from an object that some event has occurred: for
634 example, a property has changed, an animation has started or stopped, or
635 when an image has been downloaded. The \l MouseArea type, for example, has
636 a \l {MouseArea::onClicked}{clicked} signal that is emitted when the user clicks
637 within the mouse area.
638
639 An object can be notified through a \l{Signal handler attributes}
640 {signal handler} whenever it a particular signal is emitted. A signal handler
641 is declared with the syntax \e on<Signal> where \e <Signal> is the name of the
642 signal, with the first letter capitalized. The signal handler must be declared
643 within the definition of the object that emits the signal, and the handler
644 should contain the block of JavaScript code to be executed when the signal
645 handler is invoked.
646
647 For example, the \e onClicked signal handler below is declared within the
648 \l MouseArea object definition, and is invoked when the \l MouseArea is
649 clicked, causing a console message to be printed:
650
651 \qml
652 import QtQuick 2.0
653
654 Item {
655     width: 100; height: 100
656
657     MouseArea {
658         anchors.fill: parent
659         onClicked: {
660             console.log("Click!")
661         }
662     }
663 }
664 \endqml
665
666 \section3 Defining Signal Attributes
667
668 A signal may be defined for a type in C++ by registering a Q_SIGNAL of a class
669 which is then registered with the QML type system.  Alternatively, a custom
670 signal for an object type may be defined in an object declaration in a QML
671 document with the following syntax:
672
673 \code
674     signal <signalName>[([<type> <parameter name>[, ...]])]
675 \endcode
676
677 Attempting to declare two signals or methods with the same name in the same
678 type block is an error. However, a new signal may reuse the name of an existing
679 signal on the type. (This should be done with caution, as the existing signal
680 may be hidden and become inaccessible.)
681
682 Here are three examples of signal declarations:
683
684 \qml
685 import QtQuick 2.0
686
687 Item {
688     signal clicked
689     signal hovered()
690     signal actionPerformed(string action, var actionResult)
691 }
692 \endqml
693
694 If the signal has no parameters, the "()" brackets are optional. If parameters
695 are used, the parameter types must be declared, as for the \c string and \c var
696 arguments for the \c actionPerformed signal above. The allowed parameter types
697 are the same as those listed under \l {Defining Property Attributes} on this page.
698
699 To emit a signal, invoke it as a method. Any relevant
700 \l{Signal handler attributes}{signal handlers} will be invoked when the signal
701 is emitted, and handlers can use the defined signal argument names to access
702 the respective arguments.
703
704 \section3 Property Change Signals
705
706 QML types also provide built-in \e {property change signals} that are emitted
707 whenever a property value changes, as previously described in the section on
708 \l{Property attributes}{property attributes}.  See the upcoming section on
709 \l{Property change signal handlers}{property change signal handlers} for more
710 information about why these signals are useful, and how to use them.
711
712
713 \section2 Signal Handler Attributes
714
715 Signal handlers are a special sort of \l{Method attributes}{method attribute},
716 where the method implementation is invoked by the QML engine whenever the
717 associated signal is emitted.  Adding a signal to an object definition in QML
718 will automatically add an associated signal handler to the object definition,
719 which has, by default, an empty implementation.  Clients can provide an
720 implementation, to implement program logic.
721
722 Consider the following \c SquareButton type, whose definition is provided in
723 the \c SquareButton.qml file as shown below, with signals \c activated and
724 \c deactivated:
725
726 \qml
727 // SquareButton.qml
728 Rectangle {
729     id: root
730
731     signal activated(real xPosition, real yPosition)
732     signal deactivated
733
734     width: 100; height: 100
735
736     MouseArea {
737         anchors.fill: parent
738         onPressed: root.activated(mouse.x, mouse.y)
739         onRelased: root.deactivated()
740     }
741 }
742 \endqml
743
744 These signals could be received by any \c SquareButton objects in another QML
745 file in the same directory, where implementations for the signal handlers are
746 provided by the client:
747
748 \qml
749 // myapplication.qml
750 SquareButton {
751     onActivated: console.log("Activated at " + xPosition + "," + yPosition)
752     onDeactivated: console.log("Deactivated!")
753 }
754 \endqml
755
756 See the \l {Signal and Handler Event System} for more details on use of
757 signals.
758
759 \section3 Property Change Signal Handlers
760
761 Signal handlers for property change signal take the syntax form
762 \e on<Property>Changed where \e <Property> is the name of the property,
763 with the first letter capitalized. For example, although the \l TextInput type
764 documentation does not document a \c textChanged signal, this signal is
765 implicitly available through the fact that \l TextInput has a
766 \l {TextInput::text}{text} property and so it is possible to write an
767 \c onTextChanged signal handler to be called whenever this property changes:
768
769 \qml
770 import QtQuick 2.0
771
772 TextInput {
773     text: "Change this!"
774
775     onTextChanged: console.log("Text has changed to:", text)
776 }
777 \endqml
778
779
780 \section2 Method Attributes
781
782 A method of an object type is a function which may be called to perform some
783 processing or trigger further events.  A method can be connected to a signal so
784 that it is automatically invoked whenever the signal is emitted.  See
785 \l {Signal and Handler Event System} for more details.
786
787 \section3 Defining Method Attributes
788
789 A method may be defined for a type in C++ by tagging a function of a class
790 which is then registered with the QML type system with Q_INVOKABLE or by
791 registering it as a Q_SLOT of the class.  Alternatively, a custom method can
792 be added to an object declaration in a QML document with the following syntax:
793
794 \code
795     function <functionName>([<parameterName>[, ...]]) { <body> }
796 \endcode
797
798 Methods can be added to a QML type in order to define standalone, reusable
799 blocks of JavaScript code.  These methods can be invoked either internally or
800 by external objects.
801
802 Unlike signals, method parameter types do not have to be declared as they
803 default to the \c var type.
804
805 Attempting to declare two methods or signals with the same name in the same
806 type block is an error. However, a new method may reuse the name of an existing
807 method on the type. (This should be done with caution, as the existing method
808 may be hidden and become inaccessible.)
809
810 Below is a \l Rectangle with a \c calculateHeight() method that is called when
811 assigning the \c height value:
812
813 \qml
814 import QtQuick 2.0
815 Rectangle {
816     id: rect
817
818     function calculateHeight() {
819         return rect.width / 2;
820     }
821
822     width: 100
823     height: calculateHeight()
824 }
825 \endqml
826
827 If the method has parameters, they are accessible by name within the method.
828 Below, when the \l MouseArea is clicked it invokes the \c moveTo() method which
829 can then refer to the received \c newX and \c newY parameters to reposition the
830 text:
831
832 \qml
833 import QtQuick 2.0
834
835 Item {
836     width: 200; height: 200
837
838     MouseArea {
839         anchors.fill: parent
840         onClicked: label.moveTo(mouse.x, mouse.y)
841     }
842
843     Text {
844         id: label
845
846         function moveTo(newX, newY) {
847             label.x = newX;
848             label.y = newY;
849         }
850
851         text: "Move me!"
852     }
853 }
854 \endqml
855
856
857 \section2 Attached Properties and Attached Signal Handlers
858
859 \e {Attached properties} and \e {attached signal handlers} are mechanisms that
860 enable objects to be annotated with extra properties or signal handlers that
861 are otherwise unavailable to the object. In particular, they allow objects to
862 access properties or signals that are specifically relevant to the individual
863 object.
864
865 A QML type implementation may choose to create an \e {attaching type} with
866 particular properties and signals. Instances of this type can then be created
867 and \e attached to specific objects at run time, allowing those objects to
868 access the properties and signals of the attaching type. These are accessed by
869 prefixing the properties and respective signal handlers with the name of the
870 attaching type.
871
872 References to attached properties and handlers take the following syntax form:
873
874 \code
875 <AttachingType>.<propertyName>
876 <AttachingType>.on<SignalName>
877 \endcode
878
879 For example, the \l ListView type has an attached property
880 \l {ListView::isCurrentItem}{ListView.isCurrentItem} that is available to each delegate object in a
881 ListView. This can be used by each individual delegate object to determine
882 whether it is the currently selected item in the view:
883
884 \qml
885 import QtQuick 2.0
886
887 ListView {
888     width: 240; height: 320
889     model: 3
890     delegate: Rectangle {
891         width: 100; height: 30
892         color: ListView.isCurrentItem ? "red" : "yellow"
893     }
894 }
895 \endqml
896
897 In this case, the name of the \e {attaching type} is \c ListView and the
898 property in question is \c isCurrentItem, hence the attached property is
899 referred to as \c ListView.isCurrentItem.
900
901 An attached signal handler is referred to in the same way. For example, the
902 \c Component.isCompleted attached signal handler is commonly used to execute
903 some JavaScript code when a component's creation process has been completed.
904 In the example below, once the \l ListModel has been fully created, its
905 \c Component.onCompleted signal handler will automatically be invoked to
906 populate the model:
907
908 \qml
909 import QtQuick 2.0
910
911 ListView {
912     width: 240; height: 320
913     model: ListModel {
914         id: listModel
915         Component.onCompleted: {
916             for (var i = 0; i < 10; i++)
917                 listModel.append({"Name": "Item " + i})
918         }
919     }
920     delegate: Text { text: index }
921 }
922 \endqml
923
924 Since the name of the \e {attaching type} is \c Component and that type has a
925 \c completed signal, the attached signal handler is referred to as
926 \c Component.isCompleted.
927
928
929 \section3 A Note About Accessing Attached Properties and Signal Handlers
930
931 A common error is to assume that attached properties and signal handlers are
932 directly accessible from the children of the object to which these attributes
933 have been attached. This is not the case. The instance of the
934 \e {attaching type} is only attached to specific objects, not to the object
935 and all of its children.
936
937 For example, below is a modified version of the earlier example involving
938 attached properties. This time, the delegate is an \l Item and the colored
939 \l Rectangle is a child of that item:
940
941 \qml
942 import QtQuick 2.0
943
944 ListView {
945     width: 240; height: 320
946     model: 3
947     delegate: Item {
948         width: 100; height: 30
949
950         Rectangle {
951             width: 100; height: 30
952             color: ListView.isCurrentItem ? "red" : "yellow"    // WRONG! This won't work.
953         }
954     }
955 }
956 \endqml
957
958 This does not work as expected because \c ListView.isCurrentItem is attached
959 \e only to the root delegate object, and not its children. Since the
960 \l Rectangle is a child of the delegate, rather than being the delegate itself,
961 it cannot access the \c isCurrentItem attached property as
962 \c ListView.isCurrentItem. So instead, the rectangle should access
963 \c isCurrentItem through the root delegate:
964
965 \qml
966 ListView {
967     //....
968     delegate: Item {
969         id: delegateItem
970         width: 100; height: 30
971
972         Rectangle {
973             width: 100; height: 30
974             color: delegateItem.ListView.isCurrentItem ? "red" : "yellow"   // correct
975         }
976     }
977 }
978 \endqml
979
980 Now \c delegateItem.ListView.isCurrentItem correctly refers to the
981 \c isCurrentItem attached property of the delegate.
982
983 */