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