Qt 6.x
The Qt SDK
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
9Most applications need to format data and display the data. Qt Quick has the
10notion of \e models, \e views, and \e delegates to display data. They modularize
11the visualization of data in order to give the developer or designer control
12over the different aspects of the data. A developer can swap a list view with a
13grid view with little changes to the data. Similarly, encapsulating an instance
14of the data in a delegate allows the developer to dictate how to present or
15handle the data.
16
17\image modelview-overview.png
18\list
19\li \b Model - contains the data and its structure. There are several QML
20types for creating models.
21\li \b View - a container that displays the data. The view might
22display the data in a list or a grid.
23\li \b Delegate - dictates how the data should appear in the view.
24The delegate takes each unit of data in the model and encapsulates it. The data is
25accessible through the delegate. The delegate can also write data
26back into editable models (e.g. in a TextField's onAccepted Handler).
27\endlist
28
29To 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 Accessing Views and Models from Delegates
121
122 The list view to which the delegate is bound is accessible from the delegate
123 through the \c{ListView.view} property. Likewise, the GridView
124 \c{GridView.view} is available to delegates. The corresponding model and its
125 properties, therefore, are available through \c{ListView.view.model}. In
126 addition, any defined signals or methods in the model are also accessible.
127
128 This mechanism is useful when you want to use the same delegate for a number
129 of views, for example, but you want decorations or other features to be
130 different for each view, and you would like these different settings to be
131 properties of each of the views. Similarly, it might be of interest to
132 access or show some properties of the model.
133
134 In the following example, the delegate shows the property \e{language} of
135 the model, and the color of one of the fields depends on the property
136 \e{fruit_color} of the view.
137
138 \snippet qml/models/views-models-delegates.qml rectangle
139
140\target qml-data-models
141\section1 Models
142
143 Data is provided to the delegate via named data roles which the delegate may
144 bind to. Here is a ListModel with two roles, \e type and \e age, and a
145 ListView with a delegate that binds to these roles to display their values:
146
147 \snippet qml/qml-data-models/listmodel-listview-required.qml document
148
149 In most cases you should use \l{Required Properties}{required properties} to
150 pass model data into your delegates. If a delegate contains required
151 properties, the QML engine will check if the name of a required property
152 matches that of a model role. If so, that property will be bound to the
153 corresponding value from the model.
154
155 In rare corner cases, you may want to transfer the model properties through
156 the QML context rather than as required properties. If no required
157 properties are present in your delegate, the named roles are provided as
158 context properties:
159
160 \snippet qml/qml-data-models/listmodel-listview.qml document
161
162 Context properties are invisible to tooling and prevent the
163 \l{Qt Quick Compiler} from optimizing your code. They make it harder to
164 reason about the specific data your delegate expects. There is no way to
165 explicitly populate the QML context from QML. If your component expects
166 data to be passed via the QML context, you can only use it in places
167 where the right context is made available via native means. This can be
168 your own C++ code or the specific implementations of surrounding elements.
169 Conversely, required properties can be set in a number of ways from QML or
170 via native means. Therefore, passing data via the QML context reduces the
171 re-usability of your components.
172
173 If there is a naming clash between the model's properties and the delegate's
174 properties, the roles can be accessed with the qualified \e model name
175 instead. For example, if a \l Text type had (non-required) \e type or \e age
176 properties, the text in the above example would display those property
177 values instead of the \e type and \e age values from the model item. In this
178 case, the properties could have been referenced as \c model.type and
179 \c model.age instead to ensure the delegate displays the property values from
180 the model item. For this to work, you need to require a \c model property in
181 your delegate (unless you are using context properties).
182
183 A special \e index role containing the index of the item in the model is
184 also available to the delegate. Note this index is set to -1 if the item is
185 removed from the model. If you bind to the index role, be sure that the
186 logic accounts for the possibility of index being -1, i.e. that the item is
187 no longer valid. (Usually the item will shortly be destroyed, but it is
188 possible to delay delegate destruction in some views via a \c delayRemove
189 attached property.)
190
191 Remember that you can use integers or arrays as model:
192
193 \qml
194 Repeater {
195 model: 5
196 Text {
197 required property int modelData
198 text: modelData
199 }
200 }
201 \endqml
202
203 \qml
204 Repeater {
205 model: ["one", "two", "three"]
206 Text {
207 required property string modelData
208 text: modelData
209 }
210 }
211 \endqml
212
213 Such models provide a singular, anonymous piece of data to each instance
214 of the delegate. Accessing this piece of data is the primary reason to
215 use \e modelData, but other models also provide \e modelData.
216
217 The object provided via the \e model role has a property with an empty name.
218 This anonymous property holds the \e modelData. Furthermore, the object
219 provided via the \e model role has another property called \e modelData.
220 This property is deprecated and also holds the \e modelData.
221
222 In addition to the \e model role, a \e modelData role is provided. The
223 \e modelData role holds the same data as the \e modelData property and the
224 anonymous property of the object provided via the \e model role.
225
226 The differences between the \e model role and the various means to access
227 \e modelData are as follows:
228
229 \list
230 \li Models that do not have named roles (such as integers or an array of
231 strings) have their data provided via the \e modelData role. The
232 \e modelData role does not necessarily contain an object in this case.
233 In the case of an integer model it would contain an integer (the index
234 of the current model item). In the case of an array of strings it would
235 contain a string. The \e model role still contains an object, but
236 without any properties for named roles. \e model still contains its
237 usual \e modelData and anonymous properties, though.
238 \li If the model has only one named role, the \e modelData role contains
239 the same data as the named role. It is not necessarily an object and it
240 does not contain the named role as a named property the way it usually
241 would. The \e model role still contains an object with the named role as
242 property, and the \e modelData and anonymous properties in this case.
243 \li For models with multiple roles, the \e modelData role is only provided as
244 a required property, not as a context property. This is due to backwards
245 compatibility with older versions of Qt.
246 \endlist
247
248 The anonymous property on \e model allows you to cleanly write delegates
249 that receive both their model data and the role name they should react
250 to as properties from the outside. You can provide a model without or
251 with only one named role, and an empty string as role. Then, a binding that
252 simply accesses \c{model[role]} will do what you expect. You don't have to
253 add special code for this case.
254
255 \note The \e model, \e index, and \e modelData roles are not accessible
256 if the delegate contains required properties, unless it has also required
257 properties with matching names.
258
259 QML provides several types of data models among the built-in set of QML
260 types. In addition, models can be created with Qt C++ and then made
261 available to \l{QQmlEngine} for use by
262 QML components. For information about creating these models, visit the
263 \l{Using C++ Models with Qt Quick Views}
264 and \l{qtqml-typesystem-topic.html#qml-object-types}
265 {creating QML types} articles.
266
267 Positioning of items from a model can be achieved using a \l{Repeater}.
268
269 \section2 List Model
270
271 ListModel is a simple hierarchy of types specified in QML. The
272 available roles are specified by the \l ListElement properties.
273
274 \snippet qml/qml-data-models/listelements.qml model
275
276 The above model has two roles, \e name and \e cost. These can be bound
277 to by a ListView delegate, for example:
278
279 \snippet qml/qml-data-models/listelements.qml view
280
281 ListModel provides methods to manipulate the ListModel directly via JavaScript.
282 In this case, the first item inserted determines the roles available
283 to any views that are using the model. For example, if an empty ListModel is
284 created and populated via JavaScript, the roles provided by the first
285 insertion are the only roles that will be shown in the view:
286
287 \snippet qml/qml-data-models/dynamic-listmodel.qml model
288 \dots
289 \snippet qml/qml-data-models/dynamic-listmodel.qml mouse area
290
291 When the MouseArea is clicked, \c fruitModel will have two roles, \e cost and \e name.
292 Even if subsequent roles are added, only the first two will be handled by views
293 using the model. To reset the roles available in the model, call ListModel::clear().
294
295 \section2 XML Model
296
297 XmlListModel allows construction of a model from an XML data source. The roles
298 are specified via the \l [QML]{XmlListModelRole} type. The type needs to be imported.
299
300 \code
301 import QtQml.XmlListModel
302 \endcode
303
304
305 The following model has three roles, \e title, \e link and \e pubDate:
306 \qml
307 XmlListModel {
308 id: feedModel
309 source: "http://rss.news.yahoo.com/rss/oceania"
310 query: "/rss/channel/item"
311 XmlListModelRole { name: "title"; elementName: "title" }
312 XmlListModelRole { name: "link"; elementName: "link" }
313 XmlListModelRole { name: "pubDate"; elementName: "pubDate" }
314 }
315 \endqml
316
317 The \c query property specifies that the XmlListModel generates a model item
318 for each \c <item> in the XML document.
319
320 The \l{Qt Quick Demo - RSS News}{RSS News demo} shows how XmlListModel can
321 be used to display an RSS feed.
322
323 \section2 Object Model
324
325 ObjectModel contains the visual items to be used in a view. When an ObjectModel
326 is used in a view, the view does not require a delegate because the ObjectModel
327 already contains the visual delegate (items).
328
329 The example below places three colored rectangles in a ListView.
330
331 \code
332 import QtQuick 2.0
333 import QtQml.Models 2.1
334
335 Rectangle {
336 ObjectModel {
337 id: itemModel
338 Rectangle { height: 30; width: 80; color: "red" }
339 Rectangle { height: 30; width: 80; color: "green" }
340 Rectangle { height: 30; width: 80; color: "blue" }
341 }
342
343 ListView {
344 anchors.fill: parent
345 model: itemModel
346 }
347 }
348 \endcode
349
350 \section2 Integers as Models
351
352 An integer can be used as a model that contains a certain number
353 of types. In this case, the model does not have any data roles.
354
355 The following example creates a ListView with five elements:
356 \qml
357 Item {
358 width: 200; height: 250
359
360 Component {
361 id: itemDelegate
362
363 Text {
364 required property int index
365 text: "I am item number: " + index
366 }
367 }
368
369 ListView {
370 anchors.fill: parent
371 model: 5
372 delegate: itemDelegate
373 }
374
375 }
376 \endqml
377
378 \note The limit on the number of items in an integer model is 100,000,000.
379
380 \section2 Object Instances as Models
381
382 An object instance can be used to specify a model with a single object
383 type. The properties of the object are provided as roles.
384
385 The example below creates a list with one item, showing the color of the \e
386 myText text. Note the use of the fully qualified \e model.color property to
387 avoid clashing with \e color property of the Text type in the delegate.
388
389 \qml
390 Rectangle {
391 width: 200; height: 250
392
393 Text {
394 id: myText
395 text: "Hello"
396 color: "#dd44ee"
397 }
398
399 Component {
400 id: myDelegate
401
402 Text {
403 required property var model
404 text: model.color
405 }
406 }
407
408 ListView {
409 anchors.fill: parent
410 anchors.topMargin: 30
411 model: myText
412 delegate: myDelegate
413 }
414 }
415 \endqml
416
417 \target qml-c++-models
418 \section2 C++ Data Models
419
420 Models can be defined in C++ and then made available to QML. This mechanism
421 is useful for exposing existing C++ data models or otherwise complex
422 datasets to QML.
423
424 For information, visit the
425 \l{Using C++ Models with Qt Quick Views}
426 article.
427
428 \section2 Array models
429
430 You can use JavaScript arrays and various kinds of QML lists as models.
431 The elements of the list will be made available as model and modelData
432 by the rules outlined above: Singular data like integers or strings are
433 made available as singular modelData. Structured data like JavaScript
434 objects or QObjects are made available as structured model and modelData.
435
436 The individual model roles are also made available if you request them as
437 required properties. Since we cannot know in advance what objects will
438 appear in an array, any required property in a delegate will be populated,
439 possibly with a coercion of \c undefined to the required type. The
440 individual model roles are not made available via the QML context, though.
441 They would shadow all other context properties.
442
443\section1 Repeaters
444
445\div {class="float-right"}
446\inlineimage repeater-index.png
447\enddiv
448
449Repeaters create items from a template for use with positioners, using data
450from a model. Combining repeaters and positioners is an easy way to lay out
451lots of items. A \l Repeater item is placed inside a positioner, and generates
452items that the enclosing positioner arranges.
453
454Each Repeater creates a number of items by combining each element of data
455from a model, specified using the \l{Repeater::model}{model} property, with
456the template item, defined as a child item within the Repeater.
457The total number of items is determined by the amount of data in the model.
458
459The following example shows a repeater used with a Grid item to
460arrange a set of Rectangle items. The Repeater item creates a series of 24
461rectangles for the Grid item to position in a 5 by 5 arrangement.
462
463\snippet qml/repeaters/repeater-grid-index.qml document
464
465The number of items created by a Repeater is held by its \l{Repeater::}{count}
466property. It is not possible to set this property to determine the number of
467items to be created. Instead, as in the above example, we use an integer as
468the model.
469
470For more details, see the \l{qtquick-modelviewsdata-modelview.html#integers-as-models}{QML Data Models} document.
471
472If the model is a string list, the delegate is also exposed to the usual
473read-only \c modelData property that holds the string. For example:
474
475\table
476 \row
477 \li \snippet qml/repeaters/repeater.qml modeldata
478 \li \image repeater-modeldata.png
479\endtable
480
481It is also possible to use a delegate as the template for the items created
482by a Repeater. This is specified using the \l{Repeater::}{delegate} property.
483
484\section1 Changing Model Data
485
486To change model data, you can assign updated values to the \c model properties.
487The QML ListModel is editable by default whereas C++ models must implement
488setData() to become editable. Integer and JavaScript array models are read-only.
489
490Supposed a \l{QAbstractItemModel} based C++ model that implements the
491\l{QAbstractItemModel::}{setData} method is registered as a QML type named
492\c EditableModel. Data could then be written to the model like this:
493
494\qml
495ListView {
496 anchors.fill: parent
497 model: EditableModel {}
498 delegate: TextEdit {
499 required property var model
500
501 width: ListView.view.width
502 height: 30
503 text: model.edit
504 Keys.onReturnPressed: model.edit = text
505 }
506}
507\endqml
508
509\note The \c edit role is equal to \l Qt::EditRole. See \l{QAbstractItemModel::}{roleNames}()
510for the built-in role names. However, real life models would usually register custom roles.
511
512\note If a model role is bound to a \l{Required Properties}{required property}, assigning to
513that property will not modify the model. It will instead break the binding to the model (just
514like assigning to any other property breaks existing bindings). If you want to use
515required properties and change the model data, make model also a required property and assign to
516\e model.propertyName.
517
518For more information, visit the \l{qtquick-modelviewsdata-cppmodels.html#changing-model-data}{Using C++ Models with Qt Quick Views}
519article.
520
521\section1 Using Transitions
522
523Transitions can be used to animate items that are added to, moved within,
524or removed from a positioner.
525
526Transitions for adding items apply to items that are created as part of a
527positioner, as well as those that are reparented to become children of a
528positioner.
529
530Transitions for removing items apply to items within a positioner that are
531deleted, as well as those that are removed from a positioner and given new
532parents in a document.
533
534\note Changing the opacity of items to zero will not cause them to
535disappear from the positioner. They can be removed and re-added by changing
536the visible property.
537*/