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
modelview.qdoc
Go to the documentation of this file.
1
// Copyright (C) 2017 The Qt Company Ltd.
2
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
3
4
/*!
5
\page qtquick-modelviewsdata-modelview.html
6
\title Models and Views in Qt Quick
7
\brief how to display and format data in Qt Quick
8
9
Most applications need to format data and display the data. Qt Quick has the
10
notion of \e models, \e views, and \e delegates to display data. They modularize
11
the visualization of data in order to give the developer or designer control
12
over the different aspects of the data. A developer can swap a list view with a
13
grid view with little changes to the data. Similarly, encapsulating an instance
14
of the data in a delegate allows the developer to dictate how to present or
15
handle the data.
16
17
\image modelview-overview.png
18
{Diagram showing Data flowing to Model, View, and Delegate components}
19
\list
20
\li \b Model - contains the data and its structure. There are several QML
21
types for creating models.
22
\li \b View - a container that displays the data. The view might
23
display the data in a list or a grid.
24
\li \b Delegate - dictates how the data should appear in the view.
25
The delegate takes each unit of data in the model and encapsulates it. The data is
26
accessible through the delegate. The delegate can also write data
27
back into editable models (e.g. in a TextField's onAccepted Handler).
28
\endlist
29
30
To visualize data, bind the view's \c model property to a model and the
31
\c delegate property to a component or another compatible type.
32
33
\section1 Displaying Data with Views
34
35
Views are containers for collections of items. They are feature-rich and can be
36
customizable to meet style or behavior requirements.
37
38
\target qtquick-views
39
A set of standard views are provided in the basic set of Qt Quick
40
graphical types:
41
42
\list
43
\li \l{ListView} - arranges items in a horizontal or vertical list
44
\li \l{GridView} - arranges items in a grid within the available space
45
\li \l{PathView} - arranges items on a path
46
\li \l{TableView} - arranges data from a \l QAbstractTableModel in a table
47
\li \l{TreeView} - arranges data from a \l QAbstractItemModel in a tree
48
\endlist
49
50
These types have properties and behaviors exclusive to each type.
51
Visit their respective documentation for more information.
52
53
In addition, \l{Qt Quick Controls} contains some extra views and
54
delegates that are styled according to the application style, for
55
example \l HorizontalHeaderView and \l VerticalHeaderView.
56
57
\section2 Decorating Views
58
59
Views allow visual customization through \e decoration properties such as
60
the \c header, \c footer, and \c section properties. By binding an object,
61
usually another visual object, to these properties, the views are
62
decoratable. A footer may include a \l Rectangle type showing borders
63
or a header that displays a logo on top of the list.
64
65
Suppose that a specific club wants to decorate its members list with its brand
66
colors. A member list is in a \c model and the \c delegate will display the
67
model's content.
68
\snippet qml/listview-decorations.qml model
69
\snippet qml/listview-decorations.qml delegate
70
71
The club may decorate the members list by binding visual objects to the \c
72
header and \c footer properties. The visual object may be defined inline, in
73
another file, or in a \l {Component} type.
74
75
\snippet qml/listview-decorations.qml decorations
76
\image listview-decorations.png
77
{List with highlighted Club Members header above Alice, Bob, Jane, Harry, Wendy}
78
79
\section2 Mouse and Touch Handling
80
81
The views handle dragging and flicking of their content, however they do
82
not handle touch interaction with the individual delegates. In order for the
83
delegates to react to touch input, e.g. to set the \c currentIndex, a MouseArea
84
with the appropriate touch handling logic must be provided by the delegate.
85
86
Note that if \c highlightRangeMode is set to \c StrictlyEnforceRange the
87
currentIndex will be affected by dragging/flicking the view, since the view
88
will always ensure that the \c currentIndex is within the highlight range
89
specified.
90
91
\section2 ListView Sections
92
93
\l {ListView} contents may be grouped into \e sections, where related list
94
items are labeled according to their sections. Further, the sections may be
95
decorated with \l{qml-view-delegate}{delegates}.
96
97
A list may contain a list indicating people's names and the team on which
98
team the person belongs.
99
\snippet qml/listview-sections.qml model
100
\snippet qml/listview-sections.qml delegate
101
102
The ListView type has the \c section
103
\l{qtqml-syntax-objectattributes.html#Attached-properties-and-attached-signal-handlers}
104
{attached property} that can combine adjacent and related types into a
105
section. The \c section.property determines which list
106
type property to use as sections. The \c section.criteria can dictate how the
107
section names are displayed and the \c section.delegate is similar to the views'
108
\l {qml-view-delegate}{delegate} property.
109
\snippet qml/listview-sections.qml section
110
\image listview-section.png
111
{List grouped by team: Crypto with Alice and Bob, QA with Jane and Victor, Graphics with Wendy}
112
113
\target qml-view-delegate
114
\section1 View Delegates
115
116
Views need a \e delegate to visually represent an item in a list. A view will
117
visualize each item list according to the template defined by the delegate.
118
Items in a model are accessible through the \c index property as well as the
119
item's properties.
120
\snippet qml/listview.qml delegate
121
\image listview-setup.png {List showing Cat (default), Dog, Mouse, Rabbit, Horse}
122
123
\section2 Positioning of View Delegates
124
125
The type of view will determine how the items are positioned. \l {ListView}
126
will position the items in a straight line, depending on the \l {ListView::}{orientation},
127
while a \l {GridView} can lay them out in a 2 dimentional grid. It's \b {not} recommended
128
to bind directly on \l {Item::x}{x} and \l {Item::y}{y}, since the view's layouting
129
behavior will always take precedence over any positional binding.
130
131
\section2 Accessing Views and Models from Delegates
132
133
The list view to which the delegate is bound is accessible from the delegate
134
through the \c{ListView.view} property. Likewise, the GridView
135
\c{GridView.view} is available to delegates. The corresponding model and its
136
properties, therefore, are available through \c{ListView.view.model}. In
137
addition, any defined signals or methods in the model are also accessible.
138
139
This mechanism is useful when you want to use the same delegate for a number
140
of views, for example, but you want decorations or other features to be
141
different for each view, and you would like these different settings to be
142
properties of each of the views. Similarly, it might be of interest to
143
access or show some properties of the model.
144
145
In the following example, the delegate shows the property \e{language} of
146
the model, and the color of one of the fields depends on the property
147
\e{fruit_color} of the view.
148
149
\snippet qml/models/views-models-delegates.qml rectangle
150
151
\target qml-data-models
152
\section1 Models
153
154
Data is provided to the delegate via named data roles which the delegate may
155
bind to. Here is a ListModel with two roles, \e type and \e age, and a
156
ListView with a delegate that binds to these roles to display their values:
157
158
\snippet qml/qml-data-models/listmodel-listview-required.qml document
159
160
In most cases you should use \l{Required Properties}{required properties} to
161
pass model data into your delegates. If a delegate contains required
162
properties, the QML engine will check if the name of a required property
163
matches that of a model role. If so, that property will be bound to the
164
corresponding value from the model.
165
166
In rare corner cases, you may want to transfer the model properties through
167
the QML context rather than as required properties. If no required
168
properties are present in your delegate, the named roles are provided as
169
context properties:
170
171
\snippet qml/qml-data-models/listmodel-listview.qml document
172
173
Context properties are invisible to tooling and prevent the
174
\l{Qt Quick Compiler} from optimizing your code. They make it harder to
175
reason about the specific data your delegate expects. There is no way to
176
explicitly populate the QML context from QML. If your component expects
177
data to be passed via the QML context, you can only use it in places
178
where the right context is made available via native means. This can be
179
your own C++ code or the specific implementations of surrounding elements.
180
Conversely, required properties can be set in a number of ways from QML or
181
via native means. Therefore, passing data via the QML context reduces the
182
re-usability of your components.
183
184
If there is a naming clash between the model's properties and the delegate's
185
properties, the roles can be accessed with the qualified \e model name
186
instead. For example, if a \l Text type had (non-required) \e type or \e age
187
properties, the text in the above example would display those property
188
values instead of the \e type and \e age values from the model item. In this
189
case, the properties could have been referenced as \c model.type and
190
\c model.age instead to ensure the delegate displays the property values from
191
the model item. For this to work, you need to require a \c model property in
192
your delegate (unless you are using context properties).
193
194
A special \e index role containing the index of the item in the model is
195
also available to the delegate. Note this index is set to -1 if the item is
196
removed from the model. If you bind to the index role, be sure that the
197
logic accounts for the possibility of index being -1, i.e. that the item is
198
no longer valid. (Usually the item will shortly be destroyed, but it is
199
possible to delay delegate destruction in some views via a \c delayRemove
200
attached property.)
201
202
Remember that you can use integers or arrays as model:
203
204
\qml
205
Repeater {
206
model: 5
207
Text {
208
required property int modelData
209
text: modelData
210
}
211
}
212
\endqml
213
214
\qml
215
Repeater {
216
model: ["one", "two", "three"]
217
Text {
218
required property string modelData
219
text: modelData
220
}
221
}
222
\endqml
223
224
Such models provide a singular, anonymous piece of data to each instance
225
of the delegate. Accessing this piece of data is the primary reason to
226
use \e modelData, but other models also provide \e modelData.
227
228
The object provided via the \e model role has a property with an empty name.
229
This anonymous property holds the \e modelData. Furthermore, the object
230
provided via the \e model role has another property called \e modelData.
231
This property is deprecated and also holds the \e modelData.
232
233
In addition to the \e model role, a \e modelData role is provided. The
234
\e modelData role holds the same data as the \e modelData property and the
235
anonymous property of the object provided via the \e model role.
236
237
The differences between the \e model role and the various means to access
238
\e modelData are as follows:
239
240
\list
241
\li Models that do not have named roles (such as integers or an array of
242
strings) have their data provided via the \e modelData role. The
243
\e modelData role does not necessarily contain an object in this case.
244
In the case of an integer model it would contain an integer (the index
245
of the current model item). In the case of an array of strings it would
246
contain a string. The \e model role still contains an object, but
247
without any properties for named roles. \e model still contains its
248
usual \e modelData and anonymous properties, though.
249
\li If the model has only one named role, the \e modelData role contains
250
the same data as the named role. It is not necessarily an object and it
251
does not contain the named role as a named property the way it usually
252
would. The \e model role still contains an object with the named role as
253
property, and the \e modelData and anonymous properties in this case.
254
\li For models with multiple roles, the \e modelData role is only provided as
255
a required property, not as a context property. This is due to backwards
256
compatibility with older versions of Qt.
257
\endlist
258
259
The anonymous property on \e model allows you to cleanly write delegates
260
that receive both their model data and the role name they should react
261
to as properties from the outside. You can provide a model without or
262
with only one named role, and an empty string as role. Then, a binding that
263
simply accesses \c{model[role]} will do what you expect. You don't have to
264
add special code for this case.
265
266
\note The \e model, \e index, and \e modelData roles are not accessible
267
if the delegate contains required properties, unless it has also required
268
properties with matching names.
269
270
QML provides several types of data models among the built-in set of QML
271
types. In addition, models can be created with Qt C++ and then made
272
available to \l{QQmlEngine} for use by
273
QML components. For information about creating these models, visit the
274
\l{Using C++ Models with Qt Quick Views}
275
and \l{qtqml-typesystem-topic.html#qml-object-types}
276
{creating QML types} articles.
277
278
Positioning of items from a model can be achieved using a \l{Repeater}.
279
280
\section2 List Model
281
282
ListModel is a simple hierarchy of types specified in QML. The
283
available roles are specified by the \l ListElement properties.
284
285
\snippet qml/qml-data-models/listelements.qml model
286
287
The above model has two roles, \e name and \e cost. These can be bound
288
to by a ListView delegate, for example:
289
290
\snippet qml/qml-data-models/listelements.qml view
291
292
ListModel provides methods to manipulate the ListModel directly via JavaScript.
293
In this case, the first item inserted determines the roles available
294
to any views that are using the model. For example, if an empty ListModel is
295
created and populated via JavaScript, the roles provided by the first
296
insertion are the only roles that will be shown in the view:
297
298
\snippet qml/qml-data-models/dynamic-listmodel.qml model
299
\dots
300
\snippet qml/qml-data-models/dynamic-listmodel.qml mouse area
301
302
When the MouseArea is clicked, \c fruitModel will have two roles, \e cost and \e name.
303
Even if subsequent roles are added, only the first two will be handled by views
304
using the model. To reset the roles available in the model, call ListModel::clear().
305
306
\section2 XML Model
307
308
XmlListModel allows construction of a model from an XML data source. The roles
309
are specified via the \l [QML]{XmlListModelRole} type. The type needs to be imported.
310
311
\code
312
import QtQml.XmlListModel
313
\endcode
314
315
316
The following model has three roles, \e title, \e link and \e pubDate:
317
\qml
318
XmlListModel {
319
id: feedModel
320
source: "http://rss.news.yahoo.com/rss/oceania"
321
query: "/rss/channel/item"
322
XmlListModelRole { name: "title"; elementName: "title" }
323
XmlListModelRole { name: "link"; elementName: "link" }
324
XmlListModelRole { name: "pubDate"; elementName: "pubDate" }
325
}
326
\endqml
327
328
The \c query property specifies that the XmlListModel generates a model item
329
for each \c <item> in the XML document.
330
331
The \l{Qt Quick Demo - RSS News}{RSS News demo} shows how XmlListModel can
332
be used to display an RSS feed.
333
334
\section2 Object Model
335
336
ObjectModel contains the visual items to be used in a view. When an ObjectModel
337
is used in a view, the view does not require a delegate because the ObjectModel
338
already contains the visual delegate (items).
339
340
The example below places three colored rectangles in a ListView.
341
342
\code
343
import QtQuick 2.0
344
import QtQml.Models 2.1
345
346
Rectangle {
347
ObjectModel {
348
id: itemModel
349
Rectangle { height: 30; width: 80; color: "red" }
350
Rectangle { height: 30; width: 80; color: "green" }
351
Rectangle { height: 30; width: 80; color: "blue" }
352
}
353
354
ListView {
355
anchors.fill: parent
356
model: itemModel
357
}
358
}
359
\endcode
360
361
\section2 Integers as Models
362
363
An integer can be used as a model that contains a certain number
364
of types. In this case, the model does not have any data roles.
365
366
The following example creates a ListView with five elements:
367
\qml
368
Item {
369
width: 200; height: 250
370
371
Component {
372
id: itemDelegate
373
374
Text {
375
required property int index
376
text: "I am item number: " + index
377
}
378
}
379
380
ListView {
381
anchors.fill: parent
382
model: 5
383
delegate: itemDelegate
384
}
385
386
}
387
\endqml
388
389
\note The limit on the number of items in an integer model is 100,000,000.
390
391
\section2 Object Instances as Models
392
393
An object instance can be used to specify a model with a single object
394
type. The properties of the object are provided as roles.
395
396
The example below creates a list with one item, showing the color of the \e
397
myText text. Note the use of the fully qualified \e model.color property to
398
avoid clashing with \e color property of the Text type in the delegate.
399
400
\qml
401
Rectangle {
402
width: 200; height: 250
403
404
Text {
405
id: myText
406
text: "Hello"
407
color: "#dd44ee"
408
}
409
410
Component {
411
id: myDelegate
412
413
Text {
414
required property var model
415
text: model.color
416
}
417
}
418
419
ListView {
420
anchors.fill: parent
421
anchors.topMargin: 30
422
model: myText
423
delegate: myDelegate
424
}
425
}
426
\endqml
427
428
\target qml-c++-models
429
\section2 C++ Data Models
430
431
Models can be defined in C++ and then made available to QML. This mechanism
432
is useful for exposing existing C++ data models or otherwise complex
433
datasets to QML.
434
435
For information, visit the
436
\l{Using C++ Models with Qt Quick Views}
437
article.
438
439
\section2 Array models
440
441
You can use JavaScript arrays and various kinds of QML lists as models.
442
The elements of the list will be made available as model and modelData
443
by the rules outlined above: Singular data like integers or strings are
444
made available as singular modelData. Structured data like JavaScript
445
objects or QObjects are made available as structured model and modelData.
446
447
The individual model roles are also made available if you request them as
448
required properties. Since we cannot know in advance what objects will
449
appear in an array, any required property in a delegate will be populated,
450
possibly with a coercion of \c undefined to the required type. The
451
individual model roles are not made available via the QML context, though.
452
They would shadow all other context properties.
453
454
\section1 Repeaters
455
456
\div {class="float-right"}
457
\inlineimage repeater-index.png {Text items showing I'm item 0 through I'm item 9}
458
\enddiv
459
460
Repeaters create items from a template for use with positioners, using data
461
from a model. Combining repeaters and positioners is an easy way to lay out
462
lots of items. A \l Repeater item is placed inside a positioner, and generates
463
items that the enclosing positioner arranges.
464
465
Each Repeater creates a number of items by combining each element of data
466
from a model, specified using the \l{Repeater::model}{model} property, with
467
the template item, defined as a child item within the Repeater.
468
The total number of items is determined by the amount of data in the model.
469
470
The following example shows a repeater used with a Grid item to
471
arrange a set of Rectangle items. The Repeater item creates a series of 24
472
rectangles for the Grid item to position in a 5 by 5 arrangement.
473
474
\snippet qml/repeaters/repeater-grid-index.qml document
475
476
The number of items created by a Repeater is held by its \l{Repeater::}{count}
477
property. It is not possible to set this property to determine the number of
478
items to be created. Instead, as in the above example, we use an integer as
479
the model.
480
481
For more details, see the \l{qtquick-modelviewsdata-modelview.html#integers-as-models}{QML Data Models} document.
482
483
If the model is a string list, the delegate is also exposed to the usual
484
read-only \c modelData property that holds the string. For example:
485
486
\table
487
\row
488
\li \snippet qml/repeaters/repeater.qml modeldata
489
\li \image repeater-modeldata.png {Text showing Data: apples, Data: oranges, Data: pears}
490
\endtable
491
492
It is also possible to use a delegate as the template for the items created
493
by a Repeater. This is specified using the \l{Repeater::}{delegate} property.
494
495
\section1 Changing Model Data
496
497
All the relevant views have a property called \e delegateModelAccess that governs
498
if and how you can change model data from the delegate. For most use cases you
499
should set it to \e{DelegateModel.ReadWrite}. This will allow your delegate to
500
change model data in the most flexible way. Alternately, you can set it to
501
\e{DelegateModel.ReadOnly} if you don't want the delegate to change any model data
502
at all.
503
504
The following table describes in detail all the values that the property can hold.
505
506
\table
507
\row
508
\li \e{DelegateModel.Qt5ReadWrite}
509
\li The delegate \e can assign values to any context properties provided by the
510
view in order to change the relevant model item. Furthermore, it can also
511
assign values to properties of the \c model object provided as either a
512
context property or required property to the same effect. The delegate
513
\e can't change model data by assigning values to required properties
514
populated by the view, though. If you assign a value to a required
515
property of a delegate, the binding that updates the required property
516
from the model data breaks. This leaves the required property to hold the
517
value you've assigned even if the model changes later on.
518
\e{DelegateModel.Qt5ReadWrite} is the default value of
519
\e{delegateModelAccess}.
520
\row
521
\li \e{DelegateModel.ReadOnly}
522
\li The delegate \e can't assign values to context properties provided by the
523
view, nor can it assign values to properties of the \c model object.
524
Assigning a value to a required property populated by the view does not
525
break the internal binding, neither will it change any model data. The
526
required property will hold the value assigned to it until the model
527
item changes again.
528
\row
529
\li \e{DelegateModel.ReadWrite}
530
\li The delegate \e can assign values to any context properties provided by the
531
view in order to change the relevant model item. Furthermore, it can also
532
assign values to properties of the \c model object provided as either a
533
context property or required property to the same effect. The delegate
534
\e can also change model data by assigning values to required properties
535
populated by the view. Assigning a value to a required property will
536
propagate the value to the respective model item and \e not break internal
537
bindings.
538
\endtable
539
540
Some models are objects with independent identities that the view references.
541
The original object is the sole source of truth for creating delegates. It
542
is not copied. Such models will be visibly updated when writing through delegates.
543
544
Other models do not have an independent identity and are copied when assigning
545
them to the view. For such models, only the internals of the view are updated
546
when writing through the delegate. The original model remains unchanged.
547
548
In general \l{QML Object Types} have independent identities, while
549
\l{QML Value Types} do not. So \l{ListModel}, anything derived from
550
\l{QAbstractItemModel}, as well as either a single instance of an
551
\l{QML Object Types}{object type} or a list of instances of
552
\l{QML Object Types}{object types} will be updated when passed as a model and
553
written through the delegate. However, JavaScript arrays, lists of value types,
554
or simple numbers do not receive updates when you change model data via the
555
delegate.
556
557
Furthermore, when implementing your own C++ model, you need to implement
558
\l{QAbstractItemModel::}{setData} to receive any updates passed from delegates.
559
560
Supposed a \l{QAbstractItemModel} based C++ model that implements the
561
\l{QAbstractItemModel::}{setData} method is registered as a QML type named
562
\c EditableModel. Data could then be written to the model like this:
563
564
\qml
565
ListView {
566
anchors.fill: parent
567
model: EditableModel {}
568
569
// Make sure that changes to the required property are propagated
570
delegateModelAccess: DelegateModel.ReadWrite
571
572
delegate: TextEdit {
573
required property string edit
574
575
width: ListView.view.width
576
height: 30
577
text: edit
578
Keys.onReturnPressed: edit = text
579
}
580
}
581
\endqml
582
583
You can also change model data by manipulating the \c model object like this:
584
585
\qml
586
ListView {
587
anchors.fill: parent
588
model: EditableModel {}
589
delegate: TextEdit {
590
required property QtObject model
591
592
width: ListView.view.width
593
height: 30
594
text: model.edit
595
Keys.onReturnPressed: model.edit = text
596
}
597
}
598
\endqml
599
600
\note The \c edit role is equal to \l Qt::EditRole. See \l{QAbstractItemModel::}{roleNames}()
601
for the built-in role names. However, real life models would usually register custom roles.
602
603
For more information, visit the \l{qtquick-modelviewsdata-cppmodels.html#changing-model-data}{Using C++ Models with Qt Quick Views}
604
article.
605
606
\section1 Using Transitions
607
608
Transitions can be used to animate items that are added to, moved within,
609
or removed from a positioner.
610
611
Transitions for adding items apply to items that are created as part of a
612
positioner, as well as those that are reparented to become children of a
613
positioner.
614
615
Transitions for removing items apply to items within a positioner that are
616
deleted, as well as those that are removed from a positioner and given new
617
parents in a document.
618
619
\note Changing the opacity of items to zero will not cause them to
620
disappear from the positioner. They can be removed and re-added by changing
621
the visible property.
622
*/
qtdeclarative
src
quick
doc
src
concepts
modelviewsdata
modelview.qdoc
Generated on
for Qt by
1.16.1