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