aboutsummaryrefslogtreecommitdiffstats
path: root/doc/src/qml/qmlintro.qdoc
blob: 03ee94d6d1315898992e03bff70d6cb090525103 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the documentation of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:FDL$
** GNU Free Documentation License
** Alternatively, this file may be used under the terms of the GNU Free
** Documentation License version 1.3 as published by the Free Software
** Foundation and appearing in the file included in the packaging of
** this file.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms
** and conditions contained in a signed written agreement between you
** and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

/*!
\page qml-intro.html
\title Introduction to the QML Language
\brief Introduction to the concepts and features behind QML.

QML is a declarative language designed to describe the user interface of a
program: both what it looks like, and how it behaves. In QML, a user
interface is specified as a tree of objects with properties.

This introduction is meant for those with little or no programming
experience. JavaScript is used as a scripting language in QML, so you may want
to learn a bit more about it (see the online \l{Javascript Guide}) before
diving deeper into QML. It is also helpful to have a basic understanding of
other Web technologies like HTML and JSON, but it is not required.

The examples shown in this guide are located in the
\c{examples/declarative/tutorials/qmlintro} directory within the Qt source
package. You can run then with the \l{QML Viewer} tool.

\section1 \l{QML Concepts and Syntax}
\tableofcontents{1 QML Concepts and Syntax}{section4}

\section1 \l{Composing User Interfaces with QML}
\tableofcontents{1 Composing User Interfaces with QML}{section4}

\section1 \l{User Interaction with QML}
\tableofcontents{1 User Interaction with QML}{section4}
*/

/*!
\page qml-basic-syntax.html
\brief The basic syntax and concepts of the QML language.
\contentspage Introduction to the QML Language
\previouspage Introduction to the QML Language
\nextpage Composing User Interfaces with QML
\title QML Concepts and Syntax

\tableofcontents

This chapter covers the basic syntax of the QML language through the
use of examples, introducing the concepts behind the language and
the terminology used in the reference documentation.

\div {class="float-right"}
\inlineimage declarative-qmlintro-basic-syntax.png
\enddiv
The following example shows the basic syntax of QML. When opened in
the \l{QML Viewer}{\QQV tool}, the output displayed should match the
image shown on the right: a light blue rectangle.

\snippet examples/declarative/tutorials/qmlintro/basic-syntax.qml document

In this example, we import the features defined by Qt Quick 1.0, and
we declare and create a single rectangle with width, height and color.
Let's take a look at the main points of the language introduced by
this simple example.

\section1 Importing Modules

The \c import statement imports the \c QtQuick \l{QML Modules}{module},
which contains all of the standard \l{QML Elements}. Without this import
statement, the \l Rectangle and other elements would not be available.

A specific version of a module is imported. This guarantees that the
elements imported when the application is run by the user match those
used by the developer when the application was written, ensuring that
they have the expected behavior.

\section1 Elements

The rectangle in the above example is specified by the \l Rectangle
element. When we declare objects like this, we write the element's type
followed by a pair of braces in between which additional data can be
defined for the object, such as its property values and any child objects.

\div {class="float-right"}
\inlineimage declarative-qmlintro-elements1.png
\enddiv
\snippet examples/declarative/tutorials/qmlintro/elements1.qml document

Here, we create two elements: a rectangle with an image inside it. We say that
the rectangle is the parent element and the image is its child. Since the
rectangle does not have a parent element, it is a top level element.

The position of each element in the user interface is defined relative
to the position of its parent, except for the top level element whose
position is always the top-left corner of the screen.

QML files can contain multiple elements, but \e{only one} can be a top level
element.

\div {class="float-right"}
\inlineimage declarative-qmlintro-elements2.png
\enddiv
\snippet examples/declarative/tutorials/qmlintro/elements2.qml document

In this example, we can define as many elements inside the rectangle
as we like, but we cannot define other top level elements. All the
additional elements are defined inside the light blue rectangle.

\note In the QML documentation, we refer to \e elements, \e items and
\e components, often interchangeably.

\list
\o When we talk about an \e element, we usually mean the syntactic structure,
   including the name, the opening and closing braces, and its contents.
\o An \e item is an element that has a visual appearance. All items are
   elements that inherit \l Item either directly or indirectly. For example,
   a \l Rectangle is an item, but a \l State is an element because it does
   not have an intrinsic appearance.
\o A \e component is an element that is defined to be reused. In many cases,
   components are often items, too.
\endlist

For now, we will refer to elements and items. Components are discussed in
detail later in this guide.

A list of the most common elements is described on the \l{QML Basic Elements}
page. A full list can be found on the \l{QML Elements} page.

\clearfloat
\section1 Properties

A QML element usually has various \e properties that help define the element.
For example, all items have the \l{Item::}{x} and \l{Item::}{y} properties
that define the position of the item relative to its parent item (or the
screen's origin) and \l{Item::}{width} and \l{Item::}{height} properties
that define its dimensions. All simple properties have names that begin
with a lower case letter.

\section2 Setting Properties

Properties are specified with a \c{property: value} syntax. In the above
example, we can see the \l Image object has a property named \c source,
which has been assigned the value \c{"pics/logo.png"}. The property and its
value are separated by a colon.

Properties can be specified one-per-line:

\qml
Rectangle {
    width: 100
    height: 100
}
\endqml

or you can put multiple properties on a single line:

\qml
Rectangle { width: 100; height: 100 }
\endqml

When multiple property-value pairs are specified on a single line, they
must be separated by a semicolon.

\section2 Basic Property Types

QML supports properties of many types (see \l{QML Basic Types}). The basic types
include \c int, \c real, \c bool, \c string and \c color.

\qml
Item {
    x: 10.5             // a 'real' property
    state: "details"    // a 'string' property
    focus: true         // a 'bool' property
    // ...
}
\endqml

QML properties are what is known as \e type-safe. That is, they only allow you
to assign a value that matches the property type. For example, the \c x property
of item is a real, and if you try to assign a string to it you will get an error.

\badcode
Item {
    x: "hello"  // illegal!
}
\endcode

Property values are dynamic, responding to changes in the user interface.
See the \l{#Property Change Notifications}{Property Change Notifications}
section for information on the different ways to define properties, bind
them together and react to changes.

\section2 Grouped Properties
\target dot properties

Some elements contain a set of related properties that form a logical group;
these use a "dot" or grouped notation to show this. The \l Text item is one
such item that uses groups of properties to describe the font used to
display text.

Grouped properties can be written like this:

\snippet examples/declarative/tutorials/qmlintro/grouped-properties1.qml text with grouped properties

or like this:

\snippet examples/declarative/tutorials/qmlintro/grouped-properties2.qml text with grouped properties

In the element documentation, grouped properties are shown using the "dot" notation.

\section2 List Properties

Some properties contain lists of elements, such as \l State, \l Item or
\l Transition. For example, the \l{Item::}{states} property is used like
this:

\qml
Item {
    states: [
        State { name: "stop" },
        State { name: "go" }
    ]
}
\endqml

The list is enclosed in square brackets, with a comma separating the list
elements. In cases where you are only assigning a single element to a list,
you can omit the square brackets:

\qml
Item {
    states: State { name: "stop" }
}
\endqml

Elements in the list can be accessed by index. See the \l{list}{list type}
documentation for more details about list properties and their available
operations.

\section1 Expressions

JavaScript expressions can be used to assign property values. For example:

\qml
Item {
    width: 100 * 3
    height: 50 + 22
}
\endqml

These expressions can include references to other objects and properties, in
which case a \l{Property Binding in QML}{binding} is established: when the value of
the expression changes, the property to which the expression is assigned is
automatically updated to the new value. For example:

\div {class="float-right"}
\inlineimage declarative-qmlintro-property-binding1.png
\br
\inlineimage declarative-qmlintro-property-binding2.png
\enddiv
\snippet examples/declarative/tutorials/qmlintro/property-binding.qml elements

Here, the child \l Rectangle item's \c width property is set relative to
the width of its parent. Whenever the parent's width changes, the width of
the \l Rectangle is automatically updated. This uses the special \c parent
property to refer to a parent item, which we explore in the
\l{Object Identifiers}{next section}.

This is useful for relating the size of one element to another, so that
changes to the sizes of elements in the design, or at run-time, will be
taken into account.

Property binding works with all types of properties, not just those related
to the size of an element.

\section1 Object Identifiers

Each object can be given a special \e id value that allows the object to
be identified and referred to by other objects. An \c id must begin with
a lower-case letter or an underscore, and cannot contain characters other
than letters, numbers and underscores.

For example, below we define a \l Text element and a \l Rectangle element
as children of a \l Column element. The \l Text object has an \c id value
of \c{textElement}. The Rectangle object defines its \c width property
to be the same as that of the Text object by referring to
\c{textElement.width}:

\div {class="float-right"}
\inlineimage declarative-qmlintro-object-identifiers.png
\enddiv

\snippet examples/declarative/tutorials/qmlintro/object-identifiers.qml document

An object can be referred to by its \c id from anywhere within the
\l{QML Documents}{component} in which it is declared. Therefore, an
\c id value must always be unique within a single component.
This means that a single QML file should only contain one place where
a particular \c id value is defined.

The \c id value is a special value for a QML object and should not be
thought of as an ordinary object property; for example, it is not possible
to access \c{textElement.id} in the above example. Once an object is
created, its \c id cannot be changed.

\note The \c parent value is a special identity that each element can use
to refer to its parent item. For most simple user interfaces containing
a few display items, the parent of an item will be the enclosing element
in the QML file that contains it. However, when we look at more complex
ways to arrange and display items, we will find that this is not always
the case.

\section1 Comments

Commenting in QML is similar to JavaScript.
\list
\o Single line comments start with // and finish at the end of the line.
\o Multi-line comments start with /* and finish with *\/
\endlist

Comments are ignored by the QML engine. They are useful for explaining what
you are doing; for referring back to at a later date, or for others reading
your QML files.

\snippet examples/declarative/tutorials/qmlintro/comments.qml commenting

Comments can also be used to prevent the execution of code, which is
sometimes useful for tracking down problems. In the above example, the
\l Text element will have normal opacity, since the line containing the
opacity property has been turned into a comment.

\section1 Responding to Changes

User interfaces created using QML contain items such as \l Rectangle,
\l Image and \l Text to display content, but they can also contain items
that accept user input, such as \l TextInput and \l MouseArea. When the
user interacts with these items, they emit signals to inform other
components of any change. These signals can be received by the items
themselves; this is the main way to create items that respond to the user.

\section2 Signal Handlers

Signal handlers allow JavaScript code to be executed in response to a signal.
For example, the \l MouseArea element has an \l{MouseArea::}{onClicked} handler
that can be used to respond to a mouse click. Below, we use this handler to
print a message whenever the mouse is clicked:

\snippet examples/declarative/tutorials/qmlintro/signal-handlers.qml document

All signal handlers begin with \e "on".

Some signal handlers include an optional parameter. For example
the MouseArea \l{MouseArea::}{onPressed} signal handler has a \c mouse parameter
that contains information about the mouse press. This parameter can be
referred to in the JavaScript code, as below:

\snippet examples/declarative/tutorials/qmlintro/signal-handlers-parameters.qml mouse area

\section2 Property Change Notifications

When a property changes value, it can send a signal to notify others of this change.

To receive these signals, simply create a \i{signal handler} named with an
\e on<Property>Changed syntax. For example, the \l TextInput element has a
\l{TextInput::}{text} property. When this property changes, the \c textChanged
signal is emitted. We can monitor this property for changes with the
\c onTextChanged handler.

\table
\header \o Property \o Signal \o Signal Handler
\row    \o \l{TextInput::}{text} \o \c textChanged \o \c onTextChanged
\endtable

The following code shows this in practice:

\div {class="float-right"}
\inlineimage declarative-qmlintro-property-change1.png
\br
\inlineimage declarative-qmlintro-property-change2.png
\enddiv
\snippet examples/declarative/tutorials/qmlintro/property-change.qml property change

When the user modifies the text, the expression assigned to the \c textChanged
handler will be evaluated. In this example, the text changes color when this
happens.

Similarly, the \l Rectangle element has \l{Item::}{width} and
\l{Rectangle::}{color} properties. Below, we have a \l Rectangle element
that has defined two signal handlers, \c onWidthChanged and \c onColorChanged,
which will automatically be called whenever these properties are modified:

\qml
Rectangle {
    width: 100; height: 100

    onWidthChanged: console.log("Width has changed to:", width)
    onColorChanged: console.log("Color has changed to:", color)
}
\endqml

These cause the new values of these properties to be written to the console,
which can be useful for debugging purposes.

\section2 Attached Properties
\target attached-properties

Some elements attach properties to other elements. This is used in cases
where one element needs to access features of another, but does not
inherit properties to access those features.

Attached Properties are of the form \e {<Type>.<property>} where \e <Type>
is the type of the element that attaches \e <property>.

An example of attached properties in use involves the \l Keys element which
attaches properties for handling key presses to any item. For example:

\div {class="float-right"}
\inlineimage declarative-qmlintro-attached-properties.png
\enddiv
\snippet examples/declarative/tutorials/qmlintro/attached-properties.qml attached properties

The \l Keys properties are not defined by the \l Item element. They are
defined separately and attached to the item.

Attached properties are also used by delegates to reference information about
the view they are used in. For example, the \l ListView element attaches
the \e ListView.isCurrentItem property to each delegate it creates:

\div {class="float-right"}
\inlineimage declarative-qmlintro-attached-properties-view.png
\enddiv
\snippet examples/declarative/tutorials/qmlintro/attached-properties-view.qml delegate with attached property

In effect, by attaching this property, \l ListView provides an interface
that lets the delegate access information about the current item in the
view it appears in.

The use of attached properties will be covered in more depth later in this
guide.

\omit
\section2 Default Properties

Each object type can specify one of its list or object properties as its default property.
If a property has been declared as the default property, the property tag can be omitted.

For example this code:
\qml
State {
    changes: [
        PropertyChanges {},
        PropertyChanges {}
    ]
}
\endqml

can be simplified to:

\qml
State {
    PropertyChanges {}
    PropertyChanges {}
}
\endqml

because \c changes is the default property of the \c State type.
\endomit
*/

/*!
\page qml-composing-uis.html
\contentspage Introduction to the QML Language
\previouspage QML Concepts and Syntax
\nextpage User Interaction with QML
\title Composing User Interfaces with QML
\brief How to arrange items with anchors.

\tableofcontents

In the \l{Introduction to the QML Language}{previous chapter}, we looked at
the syntax of QML and the basic building blocks that are used to create
user interfaces. For example, at a low level, we have seen that an item's
\c x and \c y properties are used to position it within its parent item.
However, when defining more complex user interfaces, especially those with
items that will move or change size, we need a way to arrange items in a
more systematic way.

\section1 Anchors and Anchor Lines

In the previous examples, all the items have been given either absolute
positions in the user interface or positions relative to their parents.
For more flexibility, both at design-time and in the case where the user
interface changes at run-time, we prefer to use anchors to arrange items.

Anchors connect items together visually, creating relationships between
their geometries. As a result, mixing absolute positioning and anchors
is only recommended in cases where the constraints imposed by each
approach do not conflict. Anchors can only be used to relate items
with their parents, children or siblings.

\section2 Anchoring within Items

Anchors can be used to generally describe how items are positioned
within the space occupied by their parents. Two of the anchors are used
to place items in this way.

The following example uses anchors to position a \l Text item in the
center of a \l Rectangle.

\div {class="float-right"}
\inlineimage declarative-qmlintro-anchors-centerin.png
\enddiv
\snippet examples/declarative/tutorials/qmlintro/anchors.qml centered text

In this case, the center of the text item is anchored to the center of
its parent item by using the \c{anchors.centerIn} grouped property.
This defines a high level description of the relationship between the two
items. Similarly, the \c{anchors.fill} grouped property is used to describe
the case where an item needs to fill the space provided by its parent.

\note When using \c{anchors.centerIn} and \c{anchors.fill}, the value of
the anchor property is an item.

\section2 Anchor Lines

At a lower level, anchors can be used to line up the edges of two items.
In the following example, the \l Text item is centered within its parent,
the \l Item that defines the user interface. The \l Rectangle uses anchors
to define its position relative to the text item.

\div {class="float-right"}
\inlineimage declarative-qmlintro-anchors-edges.png
\enddiv
\snippet examples/declarative/tutorials/qmlintro/anchors2.qml anchored items

By giving the text item the \c textItem identifier, we can refer to it when
defining the anchors for the rectangle. We line up the right edge of the
rectangle with the left edge of the text item, and line up their top edges.

This example shows the use of anchor lines. Grouped properties are defined
for key parts of each item, including its top, left, right and bottom edges,
plus the lines running through the horizontal center and vertical center of
the item. A baseline anchor line is also used for items that display text.

\note We connect anchor lines to other anchor lines, not to items.

\section2 Anchors and Property Bindings

Since the anchor definitions are property bindings, any changes to the
position of an anchor will cause any connected anchors to move as well.
This is illustrated by the following example, which places a red rectangle
beneath a \l TextInput item and uses anchors to ensure that it is always
the same width.

\div {class="float-right"}
\inlineimage declarative-qmlintro-anchors-expanding1.png
\br
\inlineimage declarative-qmlintro-anchors-expanding2.png
\enddiv
\snippet examples/declarative/tutorials/qmlintro/anchors-expanding.qml anchored items

The anchor lines on the left and right edges of the rectangle are connected
to those of the text input item. Since the text can be modified by the user,
the width of the item can change. The use of anchors causes the width of the
rectangle to change as well.

The \l{Anchor-Based Layout in QML} document covers the use of anchors in
more detail.

\clearfloat
\section2 Margins

Although anchors are useful for lining up items, it is often useful to leave
small gaps between the edges of adjacent items. The following example lines
up an \l Image item with a \l Text item, but uses a margin to leave a gap
between them.

\div {class="float-right"}
\inlineimage declarative-qmlintro-anchors-margins.png
\br
\inlineimage declarative-qmlintro-anchors-baseline-margins.png
\enddiv
\snippet examples/declarative/tutorials/qmlintro/anchors-margins.qml anchored items

Note that the image also uses a margin to leave a gap between its left edge
and the left edge of the user interface.

Adding \l Rectangle items to the scene description, we can see the effects of
the anchors and margins, with the image displaced from the left edge of its
parent item and the text label displaced from the right edge of the image.

\clearfloat
\section2 Limitations and Strategies

Anchors allow the relationships between items to be described using simple
declarations, maintaining a user interface layout when items move or change
size. They are useful in most situations, but have limitations which need
to be considered, and therefore it is a good idea to adopt strategies for
using them.

\section3 Limitations of Anchors

Since anchors can only be used to relate an item with its parent, children or
siblings, care must be taken when referencing items in complex or deeply-nested
user interfaces. Where there are lots of items to be arranged, it can be more
productive to use \l{#Positioners}{positioners} and
\l{Generating Items with Repeaters}{repeaters}, or
\l{QML Models and Views}{models and views}.

Connections between anchors cannot be deleted and will override explicit
declarations of positions and sizes using the \l{Item::}{x}, \l{Item::}{y},
\l{Item::}{width} and \l{Item::}{height} properties of items.

Since anchors rely on property binding to ensure that items are dynamically
updated if one of them changes, each anchor definition creates a new dependency
on another item. Use of anchors therefore causes a dependency graph defining an
order in which items will be updated. Problems can occur if circular dependencies
are created between items. The following example shows this occurring with a
parent item and its child.

\snippet examples/declarative/tutorials/qmlintro/circular.qml circular

\section3 Strategies for Use

In order to reference an item with an anchor, it needs a way to be identified.
Children of the item can refer to it as \c parent, but otherwise it needs to
define an \l{Introduction to the QML Language#Object Identifiers}{identifier}.
It is good practice to define identifiers for all the items that need to be
positioned or referenced in some way unless those items can be referenced
using the \c parent identifier.

It is usually helpful to identify the fixed or dominant parts of the user
interface and give those items identifiers so that dependent items can refer
to them. This avoids potential issues with circular dependencies.
In the example shown, the \c launchBox and \c cancelBox items are anchored
within the top level item that contains the user interface. Each of these
items contain an image and a text item that are anchored to their parent.

\div {class="float-right"}
\inlineimage declarative-qmlintro-anchors-strategy-annotated.png
\enddiv
\snippet examples/declarative/tutorials/qmlintro/anchors-strategy.qml anchor strategy

The above example shows how each item is anchored to its parent. This ensures
that the dependencies introduced by the anchors all consistently point to each
item's parent or a sibling. It is not always possible to ensure such simple
dependencies between items. As a result, it is often necessary to consider
other factors that determine how the use of anchors will affect the geometries
of items.

When positioning items using the \c horizontalCenter anchor, do not use the
\c left or \c right anchors; define the width of the item instead, either as
a fixed value or as a proportion of the parent item. Similarly, avoid using
the \c top or \c bottom anchors with the \c verticalCenter anchor; set the
height of the item instead.

Items that define their own width and height based on their contents, like
\l Image or \l TextInput, can be used with all kinds of anchors. Care must
be taken to avoid imposing conflicting constraints on their dimensions.
For example, using \c left and \c right anchors to position a text input
item may be problematic because the item determines its own width and it
may change.

When defining an item that you want to stretch to fill the available space
between other items, make sure that you anchor the stretchable item to items
with well-defined or implicitly-defined sizes and not the other way round.
The following example shows this with a \l Text item with an implicit size
and a \l Rectangle that stretches to fill the remaining space in its parent
item.

\div {class="float-right"}
\inlineimage declarative-qmlintro-anchors-stretch.png
\enddiv
\snippet examples/declarative/tutorials/qmlintro/anchors-stretch.qml items

The rectangle uses anchors to define its top, left and right edges in terms
of its parent item, and the bottom edge is aligned with the top of the text
item. If, instead, the text item is anchored to the rectangle, which has no
implicit size, the layout of the user interface will be broken because the
rectangle will be assigned a zero height.

\section1 Positioners

Positioner items are container items that manage the positions and sizes of
items in a declarative user interface. Positioners behave in a similar way to
the \l{Widgets and Layouts}{layout managers} used with standard Qt widgets,
except that they are also containers in their own right.

Positioners make it easier to work with many items when they need to be
arranged in a regular layout. As we will see when we encounter
\l{Generating Items with Repeaters}{Repeaters}, it is easier to describe
how items should be arranged when there are many of them than it is to
try and individually position them.

\section2 Standard Positioners

A set of standard positioners are provided in the basic set of Qt Quick items.
Since these are all based on the \l Item element, they contain properties that
define their positions and sizes, but they do not have any visual appearance
of their own; they simply arrange their child items in the space allocated to
them. Any background color, if desired, must be added to a parent Rectangle.

\list
\o \l{#Row}{Row} arranges its children in a row.
\o \l{#Column}{Column} arranges its children in a column.
\o \l{#Grid}{Grid} arranges its children in a grid.
\o \l{#Flow}{Flow} arranges its children like words on a page.
\endlist

Each of these items provides many of the same properties as the others,
making it easy to exchange one with another at a later point in the design
of an application or component. The common properties are \c spacing,
\c add and \c move. As expected, the \l{Row::spacing}, \l{Column::spacing}
and \l{Grid::spacing} properties have slightly different meanings because
they describe how space is added to different kinds of layout.

The \c add and \c move properties describe what should happen when items
are added to a positioner item or moved within it. These actions are
described with \l{QML Animation and Transitions}{transitions}, and will
be covered later.

\section3 Row

\l Row items are used to horizontally arrange items. The following example
uses a Row item to arrange three rounded \l Rectangle items in an area defined
by an outer colored Rectangle. The \l{Row::spacing}{spacing} property is set to
include a small amount of space between the rectangles.

\div {class="float-right"}
\inlineimage qml-row.png
\enddiv
\snippet examples/declarative/tutorials/qmlintro/row.qml document

We ensure that the parent \l Rectangle is large enough so that there is some space
left around the edges of the horizontally centered Row item. The equally-sized
rectangles in this example automatically line up because they each have the
same height. Items with different heights will not be positioned vertically
by the \l Row; these need to be lined up using anchors.

Since the \l Row item is responsible for positioning its child items
horizontally, those child items cannot use anchors to position themselves
within the row. However, they can use anchors to align themselves vertically
relative to one another or to the row itself. The following example uses
\c verticalCenter anchors to vertically align three rectangles with
different sizes.

\div {class="float-right"}
\inlineimage declarative-qmlintro-row-anchors.png
\enddiv
\snippet examples/declarative/tutorials/qmlintro/row-anchors.qml row

Note that the \l Row item itself uses \c horizontalCenter and \c verticalCenter
anchors to place itself in the center of its parent. It is free to do this
because it is not being positioned by its parent, a \l Rectangle. However,
when we place positioners inside other positioner, such as a \l Row inside
a \l Column, we will need to be aware of what constraints are being imposed
by the positioner's parent item. This is
\l{#Nesting Positioner Items}{discussed later} in this chapter.

The height of the row is dependent on the heights of the individual child
items and, unless specified using the \c height property or with anchors,
it will only be as high as the tallest child item.

\clearfloat
\section3 Column

\l Column items are used to vertically arrange items. The following example
uses a Column item to arrange three \l Rectangle items in an area defined
by an outer \l Item. The \l{Column::spacing}{spacing} property is set to
include a small amount of space between the rectangles.

\div {class="float-right"}
\inlineimage qml-column.png
\enddiv
\snippet examples/declarative/tutorials/qmlintro/column.qml document

In the above example, each of the rounded rectangles are positioned by the
\l Column item. The column only changes the vertical positions of its
child items and does not restrict their horizontal positions. However,
the restrictions on the use of anchors do not apply to the children of
these child items, so each \l Text item uses its \c centerIn anchor to
horizontally and vertically align itself within its parent rectangle.

The width of the column is dependent on the widths of the individual child
items and, unless specified using the \c width property or with anchors,
it will only be as wide as the widest child item.

\div {class="float-right"}
\inlineimage declarative-qmlintro-column-anchors.png
\enddiv
\snippet examples/declarative/tutorials/qmlintro/column-anchors.qml document

The example above stretches the column horizontally to fill the entire
user interface, and stretches each rectangle inside to fill the column.
The text items behave as they did in the previous example.

\clearfloat
\section3 Grid

\l Grid items are used to place items in a grid or table arrangement.
The following example uses a Grid item to place four \l Rectangle items
in a 2-by-2 grid. As with the other positioners, the spacing between items
can be specified using the \l{Grid::spacing}{spacing} property.

\div {class="float-right"}
\inlineimage qml-grid-spacing.png
\enddiv
\snippet examples/declarative/tutorials/qmlintro/grid-spacing.qml document

There is no difference between horizontal and vertical spacing inserted
between items, so any additional space must be added within the items
themselves. Any empty cells in the grid must be created by defining
placeholder items at the appropriate places in the grid definition.

As with the \l Row and \l Column items, \l Grid items restrict the anchors
used by their child items. Since they position items both horizontally
and vertically, it is not possible to use any of the anchors to align
items within the grid. However, we can use placeholder items as the grid's
child items and put visible items inside those, using anchors to align
them.

\div {class="float-right"}
\inlineimage declarative-qmlintro-grid-positioning.png
\enddiv
\snippet examples/declarative/tutorials/qmlintro/grid-positioning.qml document start
\snippet examples/declarative/tutorials/qmlintro/grid-positioning.qml document end

We only show the first item, but the principle is the same for the others.

\clearfloat
\section3 Flow

\l Flow items are used to place items like words on a page, with rows or
columns of non-overlapping items.

Flow items arrange items in a similar way to \l Grid items, with items
arranged in lines along one axis (the minor axis), and lines of items
placed next to each other along another axis (the major axis). The
direction of flow, as well as the spacing between items, are controlled
by the \l{Flow::}{flow} and \l{Flow::}{spacing} properties.

The following example shows a Flow item containing a number of \l Text
child items. These are arranged in a similar way to those shown in the
screenshots.

\div {class="float-right"}
\inlineimage qml-flow-text1.png
\br
\inlineimage qml-flow-text2.png
\enddiv
\snippet examples/declarative/tutorials/qmlintro/flow.qml document

The main differences between the \l Grid and \l Flow positioners are that
items inside a \l Flow will wrap when they run out of space on the minor
axis, and items on one line may not be aligned with items on another line
if the items do not have uniform sizes. As with grid items, there is no
independent control of spacing between items and between lines of items.

\clearfloat
\section2 Nesting Positioner Items

Since each positioner is based on \l Item, we can nest them like other
items, placing one positioner inside another. The following example shows a
\l Column that contains two \l Row positioners.

\div {class="float-right"}
\inlineimage declarative-qmlintro-nested-positioners.png
\enddiv
\snippet examples/declarative/tutorials/qmlintro/nested-positioners.qml column

The example works around the restrictions on the use of anchors mentioned
earlier by using appropriate anchors for each item. The innermost items,
\l Text and \l Rectangle, use anchors for vertical positioning within
\l Row items, which each perform horizontal positioning of their child
items.

The rows use anchors to position themselves within the \l Column item, which
arranges them vertically. The column is centered horizontally and vertically
within its parent, a non-positioning item.

\clearfloat
\section2 Strategies for Use

Positioners are intended to be used in situations where it would be
tedious to apply anchors to a number of items. For this reason, they are
also used to position dynamically created items, such as those generated
by \l Repeater items.

The items used with positioners must have a well-defined size, otherwise
positioners will not be able to determine where they should be placed,
leaving their positions undefined. When using a \l Column, it is sufficient
to give each child item a fixed height; the width can be defined using
anchors. Similarly, with a \l Row, the width of each item should be
fixed, but the height can be defined using anchors. Items used with \l Grid
and \l Flow positioners should have fixed widths and heights.
*/

/*!
\page qml-user-interaction.html
\contentspage Introduction to the QML Language
\previouspage Composing User Interfaces with QML
\nextpage Generating Items with Repeaters
\title User Interaction with QML
\brief Making items respond to user input.

\tableofcontents

So far, we have shown how to declare items and arrange them to create a user
interface. If we play a QML file using the \l{QML Viewer}, we can resize the
display window and see the items adapt to the change, but the items
themselves do not respond to user input from the keyboard or mouse.

Unlike standard Qt widgets, items do not include intrinsic support for user
interaction. The features required for interactivity are added or applied to
items.

QML provides the \l MouseArea item to handle mouse input and \l Keys and
\l KeyNavigation attached properties to handle keyboard input. These are
used with other items to make them responsive to user input.

\section1 Mouse Areas

To make items responsive to mouse clicks, we add \l MouseArea items to the
user interface, typically as children of the items we want to make
interactive. Since \l MouseArea is based on \l Item, it has a geometry, but
no visual appearance. The following example defines a mouse area with an
explicit position and size; the image shown indicates where the mouse area
is in the user interface, but it will not be visible in the running example.

\div {class="float-right"}
\inlineimage declarative-qmlintro-mousearea-annotated.png
\enddiv
\snippet examples/declarative/tutorials/qmlintro/mousearea.qml mouse area

The \l{MouseArea::}{onPressed} and \l{MouseArea::}{onReleased} definitions
are \l{QML Concepts and Syntax#Signal Handlers}{signal handlers} that
contain JavaScript code that will be executed in response to a signal. In
this case, when the mouse button is pressed or released, the code will
change the color of the background. Other signal handlers can be defined
to handle other user input, such as \l{MouseArea::}{onClicked} and
\l{MouseArea::}{onDoubleClicked}. Some require additional configuration
of the item before they will work as expected, as we shall see later.

\note It is more common to define mouse areas within items and position them
with anchors, as shown by the rest of the examples in this chapter.

\clearfloat
\section2 Handling Mouse Buttons

The following example uses an anchor to fill a \l Text item with a mouse
area, and defines two signal handlers to response to mouse button input.

\div {class="float-right"}
\inlineimage declarative-qmlintro-mouse-pressed1.png
\br
\inlineimage declarative-qmlintro-mouse-pressed2.png
\enddiv
\snippet examples/declarative/tutorials/qmlintro/mouse-pressed-signals.qml text item

The \l{MouseArea::}{onPressed} and \l{MouseArea::}{onReleased}
signal handlers are defined for the mouse area. As a result, when the user
presses a mouse button when the cursor is over the text, the color changes
to green; when the button is released, the color changes to black.

Note that the mouse area only responds to the left mouse button by default.
This is because the default value of the \l{MouseArea::}{acceptedButtons}
is \l{Qt::LeftButton}{Qt.LeftButton}. To test for other buttons, set this
property to be the combination of the buttons required (using the OR
operator), as in the following example.

\div {class="float-right"}
\inlineimage declarative-qmlintro-mouse-pressed-buttons.png
\enddiv
\snippet examples/declarative/tutorials/qmlintro/mouse-pressed-buttons.qml items

The mouse area covers the entire area of the user interface and accepts
input from both left and right buttons. Each of the rectangles defines its
color as an expression that depends on the mouse area's
\l{MouseArea::}{pressedButtons} property, testing whether the relevant
button is found in the value of this property. When a button is released,
the value is \c{Qt.NoButton}.

\note The \l{MouseArea::}{pressed} property provides information about
whether or not a button was pressed in the mouse area, but does not
provide any more than a boolean value. This can be sufficient in many
situations.

\clearfloat
\section2 Finding the Cursor Position

The \l MouseArea item contains a number of properties and signal handlers
that provide information about the mouse cursor. For example, the
\l{MouseArea::}{mouseX} and \l{MouseArea::}{mouseY} properties contain the
position of the cursor, as shown in the following example.

\div {class="float-right"}
\inlineimage declarative-qmlintro-mouse-pressed-position.png
\enddiv
\snippet examples/declarative/tutorials/qmlintro/mouse-pressed-position.qml text item

When the user presses the mouse button over the text item, the text changes
to show the coordinates within the mouse area where the press occurred. If
we need to find the mouse position outside the text item, we should make
the mouse area a child of the text item's parent and use anchors to fill
that item instead.

\clearfloat
\section2 Mouse Hover

In the previous examples, the text item and rectangles were updated only
when the mouse button was pressed. Consider a situation where we would like
to continuously update the text item with the mouse's position. In such a
case, we could try the following:

\div {class="float-right"}
\inlineimage declarative-qmlintro-mouse-pressed-position2.png
\enddiv
\snippet examples/declarative/tutorials/qmlintro/mouse-pressed-position2.qml text item

When we run this example, the text item shows the initial, default value of
the mouse area's \c mouseX and \c mouseY properties. Moving the cursor over
the text has no effect. It is only when the text item is clicked that the
text is updated.

The reason for this is that, by default, the mouse area only updates various
properties when a button is pressed. To receive continuous updates about the
mouse cursor, we need to enable \e{mouse hover} by setting its
\l{MouseArea::}{hoverEnabled} property, as shown in the following example:

\div {class="float-right"}
\inlineimage declarative-qmlintro-mouse-hover-enabled.png
\enddiv
\snippet examples/declarative/tutorials/qmlintro/mouse-hover-enabled.qml text item

With mouse hover enabled, other properties of the \l MouseArea can be
monitored. For example, the \l{MouseArea::}{containsMouse} property can be
used to determine whether the mouse cursor is over the mouse area.
Previously, we only knew when this was the case because the user had to
press a mouse button over the area.

\div {class="float-right"}
\inlineimage declarative-qmlintro-mouse-hover-containsmouse1.png
\br
\inlineimage declarative-qmlintro-mouse-hover-containsmouse2.png
\enddiv
\snippet examples/declarative/tutorials/qmlintro/mouse-hover-containsmouse.qml items

The above example uses \l{QML Concepts and Syntax#Expressions}{an expression}
to show the coordinates of the mouse cursor when it is in the mouse area,
\c area. When \c{area.containsMouse} evaluates to \c false, the \c{-}
character is shown instead.

Certain signal handlers only become useful when mouse hover is enabled.
For example, the \l{MouseArea::}{onEntered}, \l{MouseArea::}{onExited}
and \l{MouseArea::}{onPositionChanged} signal handlers will be called
when the cursor enters, exits or changes position in the area.

\section2 Dragging Items

As well as handling the low level interaction details, the \l MouseArea item
also handles drag operations if the relevant properties are set. The
following example shows how dragging is enabled for an item.

\div {class="float-right"}
\inlineimage declarative-qmlintro-mouse-drag.png
\enddiv
\snippet examples/declarative/tutorials/qmlintro/mouse-drag.qml draggable item

The item to be dragged is the \l Rectangle containing a \l MouseArea and
\l Text items. All that is required is to set the value of the
\l{MouseArea::}{drag.target} grouped property to the item we wish to enable
dragging for; in this case, the \c parent of the mouse area. When run, the
rectangle containing the text can be dragged around its parent's area.

The other \c drag grouped properties allow the dragging behavior of the
item to be restricted and fine-tuned. \l{MouseArea::}{drag.axis} can be
set to only allow dragging to occur along the x or y axes, and the range
of positions to which the target item can be dragged can be limited to
a range specified by the \l{MouseArea::}{drag.minimumX},
\l{MouseArea::}{drag.minimumY}, \l{MouseArea::}{drag.maximumX} and
\l{MouseArea::}{drag.maximumY} properties.

\clearfloat
\section2 Strategies for Use

Mouse areas are applied to a user interface by using anchors to fill the
items that need to respond to user input. This makes them responsive to
button presses by default, and to mouse movement when the
\l{MouseArea::}{hoverEnabled} property is set to \c true. When a mouse
area is not needed to provide input, its \l{MouseArea::}{enabled}
property can be set to \c false, so that it ignores user input.

When mouse buttons are pressed and released, the
\l{MouseArea::}{pressedButtons} property is updated as expected. However,
when multiple buttons are used, as in the
\l{#Handling Mouse Buttons}{example above}, the most up-to-date values
reported by this property are not necessarily propagated to the items
that use it. For this reason, it can be better to consider using signal
handlers to respond to mouse button presses and releases.


\section1 Key Handling

Another important method of user input is via the keyboard. In addition to
the \l TextInput and \l TextEdit items, which accept keyboard input for
display purposes, QML provides facilities to allow items to capture key
presses, as well as higher level features for navigation using keys.

Unlike mouse input, which uses the \l MouseArea item, key input uses two
attached properties to handle keyboard input: \l Keys and \l KeyNavigation.
These look like ordinary elements, but can be applied to any item in order
to enable keyboard input support.

\section2 Key Navigation

In desktop user interfaces, it is usually helpful to provide a way for the
user to navigate between input fields or other interactive items by pressing
navigation keys, typically the cursor keys or the \key Tab key. The
\l KeyNavigation attached property is used to define the relationships
between items to allow this kind of navigation.

The following example shows two \l Rectangle items placed in a \l Row
positioner. These are defined with identifiers, \c{leftRect} and
\c{rightRect}.

\div {class="float-right"}
\inlineimage declarative-qmlintro-key-navigation1.png
\br
\inlineimage declarative-qmlintro-key-navigation2.png
\enddiv
\snippet examples/declarative/tutorials/qmlintro/key-navigation.qml items

The \c{leftRect} rectangle attaches the
\l{KeyNavigation::right}{KeyNavigation.right} property, setting it to refer
to the \c{rightRect} rectangle. The \c{rightRect} rectangle attaches the
\l{KeyNavigation::left}{KeyNavigation.left} property, referring to the
\c{leftRect} rectangle.

Initially, the \c{leftRect} rectangle has the keyboard focus, since its
\l{Item::}{focus} property is set to \c true. When the user presses the
right cursor key, the focus is passed to the \c{rightRect} rectangle instead,
as defined by the \l KeyNavigation attached property for that item. Pressing
the left cursor key causes the focus to be passed back to \c{leftRect}
because as defined by the \l KeyNavigation attached property for
\c{rightRect}.

\clearfloat
*/

/*!
\page qml-positioning-items.html
\contentspage Introduction to the QML Language
\previouspage Composing User Interfaces with QML
\nextpage QML Tutorial
\title Generating Items with Repeaters
\brief How to generate and position items dynamically.

\tableofcontents

\section1 Repeaters

\div {class="float-right"}
\inlineimage qml-repeater-grid-index.png
\enddiv

Repeaters create items from a template for use with positioners, using data
from a model. Combining repeaters and positioners is an easy way to lay out
lots of items. A \l Repeater item is placed inside a positioner, and generates
items that the enclosing positioner arranges.

Each Repeater creates a number of items by combining each element of data
from a model, specified using the \l{Repeater::model}{model} property, with
the template item, defined as a child item within the Repeater.
The total number of items is determined by the amount of data in the model.

The following example shows a repeater used with a \l{#Grid}{Grid} item to
arrange a set of Rectangle items. The Repeater item creates a series of 24
rectangles for the Grid item to position in a 5 by 5 arrangement.

\clearfloat
\snippet doc/src/snippets/declarative/repeaters/repeater-grid-index.qml document

The number of items created by a Repeater is held by its \l{Repeater::}{count}
property. It is not possible to set this property to determine the number of
items to be created. Instead, as in the above example, we use an integer as
the model. This is explained in the \l{QML Data Models#An Integer}{QML Data Models}
document.

It is also possible to use a delegate as the template for the items created
by a Repeater. This is specified using the \l{Repeater::}{delegate} property.

\section1 Using Transitions

Transitions can be used to animate items that are added to, moved within,
or removed from a positioner.

Transitions for adding items apply to items that are created as part of a
positioner, as well as those that are reparented to become children of a
positioner.
Transitions for removing items apply to items within a positioner that are
deleted, as well as those that are removed from a positioner and given new
parents in a document.

Additionally, changing the opacity of items to zero will cause them to
disappear using the remove transition, and making the opacity non-zero will
cause them to appear using the add transition.

\section1 Other Ways to Position Items

There are several other ways to position items in a user interface. In addition
to the basic technique of specifying their coordinates directly, they can be
positioned relative to other items with \l{anchor-layout}{anchors}, or used
with \l{QML Data Models} such as
\l{QML Data Models#VisualItemModel}{VisualItemModel}.
*/