1// Copyright (C) 2017 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
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
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
17\image modelview-overview.png
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).
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.
32\section1 Displaying Data with Views
34 Views are containers for collections of items. They are feature-rich and can be
35 customizable to meet style or behavior requirements.
38 A set of standard views are provided in the basic set of Qt Quick
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
49 These types have properties and behaviors exclusive to each type.
50 Visit their respective documentation for more information.
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.
56 \section2 Decorating Views
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.
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
67 \snippet qml/listview-decorations.qml model
68 \snippet qml/listview-decorations.qml delegate
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.
74 \snippet qml/listview-decorations.qml decorations
75 \image listview-decorations.png
77 \section2 Mouse and Touch Handling
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.
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
89 \section2 ListView Sections
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}.
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
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
110\target qml-view-delegate
111\section1 View Delegates
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
117 \snippet qml/listview.qml delegate
118 \image listview-setup.png
120 \section2 Positioning of View Delegates
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.
128 \section2 Accessing Views and Models from Delegates
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.
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.
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.
146 \snippet qml/models/views-models-delegates.qml rectangle
148\target qml-data-models
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:
155 \snippet qml/qml-data-models/listmodel-listview-required.qml document
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.
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
168 \snippet qml/qml-data-models/listmodel-listview.qml document
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.
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).
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
199 Remember that you can use integers or arrays as model:
205 required property int modelData
213 model: ["one", "two", "three"]
215 required property string modelData
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.
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.
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.
234 The differences between the \e model role and the various means to access
235 \e modelData are as follows:
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.
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.
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.
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.
275 Positioning of items from a model can be achieved using a \l{Repeater}.
279 ListModel is a simple hierarchy of types specified in QML. The
280 available roles are specified by the \l ListElement properties.
282 \snippet qml/qml-data-models/listelements.qml model
284 The above model has two roles, \e name and \e cost. These can be bound
285 to by a ListView delegate, for example:
287 \snippet qml/qml-data-models/listelements.qml view
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:
295 \snippet qml/qml-data-models/dynamic-listmodel.qml model
297 \snippet qml/qml-data-models/dynamic-listmodel.qml mouse area
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().
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.
309 import QtQml.XmlListModel
313 The following model has three roles, \e title, \e link and \e pubDate:
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" }
325 The \c query property specifies that the XmlListModel generates a model item
326 for each \c <item> in the XML document.
328 The \l{Qt Quick Demo - RSS News}{RSS News demo} shows how XmlListModel can
329 be used to display an RSS feed.
331 \section2 Object Model
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).
337 The example below places three colored rectangles in a ListView.
341 import QtQml.Models 2.1
346 Rectangle { height: 30; width: 80; color: "red" }
347 Rectangle { height: 30; width: 80; color: "green" }
348 Rectangle { height: 30; width: 80; color: "blue" }
358 \section2 Integers as Models
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.
363 The following example creates a ListView with five elements:
366 width: 200; height: 250
372 required property int index
373 text: "I am item number: " + index
380 delegate: itemDelegate
386 \note The limit on the number of items in an integer model is 100,000,000.
388 \section2 Object Instances as Models
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.
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.
399 width: 200; height: 250
411 required property var model
418 anchors.topMargin: 30
425 \target qml-c++-models
426 \section2 C++ Data Models
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
432 For information, visit the
433 \l{Using C++ Models with Qt Quick Views}
436 \section2 Array models
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.
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.
453\div {class="float-right"}
454\inlineimage repeater-index.png
457Repeaters create items from a template for use with positioners, using data
458from a model. Combining repeaters and positioners is an easy way to lay out
459lots of items. A \l Repeater item is placed inside a positioner, and generates
460items that the enclosing positioner arranges.
462Each Repeater creates a number of items by combining each element of data
463from a model, specified using the \l{Repeater::model}{model} property, with
464the template item, defined as a child item within the Repeater.
465The total number of items is determined by the amount of data in the model.
467The following example shows a repeater used with a Grid item to
468arrange a set of Rectangle items. The Repeater item creates a series of 24
469rectangles for the Grid item to position in a 5 by 5 arrangement.
471\snippet qml/repeaters/repeater-grid-index.qml document
473The number of items created by a Repeater is held by its \l{Repeater::}{count}
474property. It is not possible to set this property to determine the number of
475items to be created. Instead, as in the above example, we use an integer as
478For more details, see the \l{qtquick-modelviewsdata-modelview.html#integers-as-models}{QML Data Models} document.
480If the model is a string list, the delegate is also exposed to the usual
481read-only \c modelData property that holds the string. For example:
485 \li \snippet qml/repeaters/repeater.qml modeldata
486 \li \image repeater-modeldata.png
489It is also possible to use a delegate as the template for the items created
490by a Repeater. This is specified using the \l{Repeater::}{delegate} property.
492\section1 Changing Model Data
494To change model data, you can assign updated values to the \c model properties.
495The QML ListModel is editable by default whereas C++ models must implement
496setData() to become editable. Integer and JavaScript array models are read-only.
498Supposed a \l{QAbstractItemModel} based C++ model that implements the
499\l{QAbstractItemModel::}{setData} method is registered as a QML type named
500\c EditableModel. Data could then be written to the model like this:
505 model: EditableModel {}
507 required property var model
509 width: ListView.view.width
512 Keys.onReturnPressed: model.edit = text
517\note The \c edit role is equal to \l Qt::EditRole. See \l{QAbstractItemModel::}{roleNames}()
518for the built-in role names. However, real life models would usually register custom roles.
520\note If a model role is bound to a \l{Required Properties}{required property}, assigning to
521that property will not modify the model. It will instead break the binding to the model (just
522like assigning to any other property breaks existing bindings). If you want to use
523required properties and change the model data, make model also a required property and assign to
524\e model.propertyName.
526For more information, visit the \l{qtquick-modelviewsdata-cppmodels.html#changing-model-data}{Using C++ Models with Qt Quick Views}
529\section1 Using Transitions
531Transitions can be used to animate items that are added to, moved within,
532or removed from a positioner.
534Transitions for adding items apply to items that are created as part of a
535positioner, as well as those that are reparented to become children of a
538Transitions for removing items apply to items within a positioner that are
539deleted, as well as those that are removed from a positioner and given new
540parents in a document.
542\note Changing the opacity of items to zero will not cause them to
543disappear from the positioner. They can be removed and re-added by changing