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