Initial import from the monolithic Qt.
[profile/ivi/qtdeclarative.git] / doc / src / declarative / qdeclarativemodels.qdoc
1 /****************************************************************************
2 **
3 ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
6 **
7 ** This file is part of the documentation of the Qt Toolkit.
8 **
9 ** $QT_BEGIN_LICENSE:FDL$
10 ** No Commercial Usage
11 ** This file contains pre-release code and may not be distributed.
12 ** You may use this file in accordance with the terms and conditions
13 ** contained in the Technology Preview License Agreement accompanying
14 ** this package.
15 **
16 ** GNU Free Documentation License
17 ** Alternatively, this file may be used under the terms of the GNU Free
18 ** Documentation License version 1.3 as published by the Free Software
19 ** Foundation and appearing in the file included in the packaging of this
20 ** file.
21 **
22 ** If you have questions regarding the use of this file, please contact
23 ** Nokia at qt-info@nokia.com.
24 ** $QT_END_LICENSE$
25 **
26 ****************************************************************************/
27
28 /*!
29 \page qdeclarativemodels.html
30 \ingroup qml-features
31 \contentspage QML Features
32 \previouspage {QML Animation and Transitions}{Animation and Transitions}
33 \nextpage {Presenting Data with Views}
34 \target qmlmodels
35 \title QML Data Models
36
37 QML items such as ListView, GridView and \l Repeater require Data Models
38 that provide the data to be displayed.
39 These items typically require a \e delegate component that
40 creates an instance for each item in the model.  Models may be static, or
41 have items modified, inserted, removed or moved dynamically.
42
43 Data is provided to the delegate via named data roles which the
44 delegate may bind to. Here is a ListModel with two roles, \e type and \e age,
45 and a ListView with a delegate that binds to these roles to display their
46 values:
47
48 \snippet doc/src/snippets/declarative/qml-data-models/listmodel-listview.qml document
49
50 If there is a naming clash between the model's properties and the delegate's
51 properties, the roles can be accessed with the qualified \e model name instead.
52 For example, if a \l Text element had \e type or \e age properties, the text in the
53 above example would display those property values instead of the \e type and \e age values
54 from the model item. In this case, the properties could have been referenced as
55 \c model.type and \c model.age instead to ensure the delegate displays the
56 property values from the model item.
57
58 A special \e index role containing the index of the item in the model
59 is also available to the delegate.  Note this index is set to -1 if the item is removed from
60 the model.  If you bind to the index role, be sure that the logic
61 accounts for the possibility of index being -1, i.e. that the item
62 is no longer valid. (Usually the item will shortly be destroyed, but
63 it is possible to delay delegate destruction in some views via a \c delayRemove
64 attached property.)
65
66 Models that do not have named roles (such as the QStringList model shown below)
67 will have the data provided via the \e modelData role.  The \e modelData role is also provided for
68 models that have only one role.  In this case the \e modelData role
69 contains the same data as the named role.
70
71 QML provides several types of data models among the built-in set of
72 QML elements. In addition, models can be created with C++ and then
73 made available to QML components.
74
75 The views used to access data models are described in the
76 \l{Presenting Data with Views} overview.
77 The use of positioner items to arrange items from a model is covered in
78 \l{Using QML Positioner and Repeater Items}.
79
80
81 \keyword qml-data-models
82 \section1 QML Data Models
83
84 \section2 ListModel
85
86 ListModel is a simple hierarchy of elements specified in QML.  The
87 available roles are specified by the \l ListElement properties.
88
89 \snippet doc/src/snippets/declarative/qml-data-models/listelements.qml model
90
91 The above model has two roles, \e name and \e cost.  These can be bound
92 to by a ListView delegate, for example:
93
94 \snippet doc/src/snippets/declarative/qml-data-models/listelements.qml view
95
96 ListModel provides methods to manipulate the ListModel directly via JavaScript.
97 In this case, the first item inserted determines the roles available
98 to any views that are using the model. For example, if an empty ListModel is
99 created and populated via JavaScript, the roles provided by the first
100 insertion are the only roles that will be shown in the view:
101
102 \snippet doc/src/snippets/declarative/qml-data-models/dynamic-listmodel.qml model
103 \dots
104 \snippet doc/src/snippets/declarative/qml-data-models/dynamic-listmodel.qml mouse area
105
106 When the MouseArea is clicked, \c fruitModel will have two roles, \e cost and \e name.
107 Even if subsequent roles are added, only the first two will be handled by views
108 using the model. To reset the roles available in the model, call ListModel::clear().
109
110
111 \section2 XmlListModel
112
113 XmlListModel allows construction of a model from an XML data source. The roles
114 are specified via the \l XmlRole element.
115
116 The following model has three roles, \e title, \e link and \e description:
117 \qml
118 XmlListModel {
119      id: feedModel
120      source: "http://rss.news.yahoo.com/rss/oceania"
121      query: "/rss/channel/item"
122      XmlRole { name: "title"; query: "title/string()" }
123      XmlRole { name: "link"; query: "link/string()" }
124      XmlRole { name: "description"; query: "description/string()" }
125 }
126 \endqml
127
128 The \l{demos/declarative/rssnews}{RSS News demo} shows how XmlListModel can
129 be used to display an RSS feed.
130
131
132 \section2 VisualItemModel
133
134 VisualItemModel allows QML items to be provided as a model.
135
136 This model contains both the data and delegate; the child items of a
137 VisualItemModel provide the contents of the delegate. The model
138 does not provide any roles.
139
140 \snippet doc/src/snippets/declarative/models/visual-model-and-view.qml visual model and view
141
142 Note that in the above example there is no delegate required.
143 The items of the model itself provide the visual elements that
144 will be positioned by the view.
145
146 \keyword qml-c++-models
147 \section1 C++ Data Models
148
149 Models can be defined in C++ and then made available to QML. This is useful
150 for exposing existing C++ data models or otherwise complex datasets to QML.
151
152 A C++ model class can be defined as a QStringList, a QList<QObject*> or a
153 QAbstractItemModel. The first two are useful for exposing simpler datasets,
154 while QAbstractItemModel provides a more flexible solution for more complex
155 models.
156
157
158 \section2 QStringList-based model
159
160 A model may be a simple QStringList, which provides the contents of the list via the \e modelData role.
161
162 Here is a ListView with a delegate that references its model item's
163 value using the \c modelData role:
164
165 \snippet examples/declarative/modelviews/stringlistmodel/view.qml 0
166
167 A Qt application can load this QML document and set the value of \c myModel
168 to a QStringList:
169
170 \snippet examples/declarative/modelviews/stringlistmodel/main.cpp 0
171
172 The complete example is available in Qt's \l {declarative/modelviews/stringlistmodel}{examples/declarative/modelviews/stringlistmodel} directory.
173
174 \note There is no way for the view to know that the contents of a QStringList
175 have changed.  If the QStringList changes, it will be necessary to reset
176 the model by calling QDeclarativeContext::setContextProperty() again.
177
178
179 \section2 QObjectList-based model
180
181 A list of QObject* values can also be used as a model. A QList<QObject*> provides
182 the properties of the objects in the list as roles.
183
184 The following application creates a \c DataObject class that with
185 Q_PROPERTY values that will be accessible as named roles when a
186 QList<DataObject*> is exposed to QML:
187
188 \snippet examples/declarative/modelviews/objectlistmodel/dataobject.h 0
189 \dots 4
190 \snippet examples/declarative/modelviews/objectlistmodel/dataobject.h 1
191 \codeline
192 \snippet examples/declarative/modelviews/objectlistmodel/main.cpp 0
193 \dots
194
195 The QObject* is available as the \c modelData property.  As a convenience,
196 the properties of the object are also made available directly in the
197 delegate's context. Here, \c view.qml references the \c DataModel properties in
198 the ListView delegate:
199
200 \snippet examples/declarative/modelviews/objectlistmodel/view.qml 0
201
202 Note the use of the fully qualified access to the \c color property.
203 The properties of the object are not replicated in the \c model
204 object, since they are easily available via the \c modelData
205 object.
206
207 The complete example is available in Qt's \l {declarative/modelviews/objectlistmodel}{examples/declarative/modelviews/objectlistmodel} directory.
208
209 Note: There is no way for the view to know that the contents of a QList
210 have changed.  If the QList changes, it will be necessary to reset
211 the model by calling QDeclarativeContext::setContextProperty() again.
212
213
214 \section2 QAbstractItemModel
215
216 A model can be defined by subclassing QAbstractItemModel. This is the
217 best approach if you have a more complex model that cannot be supported
218 by the other approaches. A QAbstractItemModel can also automatically
219 notify a QML view when the model data has changed.
220
221 The roles of a QAbstractItemModel subclass can be exposed to QML by calling
222 QAbstractItemModel::setRoleNames(). The default role names set by Qt are:
223
224 \table
225 \header
226 \o Qt Role
227 \o QML Role Name
228 \row
229 \o Qt::DisplayRole
230 \o display
231 \row
232 \o Qt::DecorationRole
233 \o decoration
234 \endtable
235
236 Here is an application with a QAbstractListModel subclass named \c AnimalModel
237 that has \e type and \e size roles. It calls QAbstractItemModel::setRoleNames() to set the
238 role names for accessing the properties via QML:
239
240 \snippet examples/declarative/modelviews/abstractitemmodel/model.h 0
241 \dots
242 \snippet examples/declarative/modelviews/abstractitemmodel/model.h 1
243 \dots
244 \snippet examples/declarative/modelviews/abstractitemmodel/model.h 2
245 \codeline
246 \snippet examples/declarative/modelviews/abstractitemmodel/model.cpp 0
247 \codeline
248 \snippet examples/declarative/modelviews/abstractitemmodel/main.cpp 0
249 \dots
250
251 This model is displayed by a ListView delegate that accesses the \e type and \e size
252 roles:
253
254 \snippet examples/declarative/modelviews/abstractitemmodel/view.qml 0
255
256 QML views are automatically updated when the model changes. Remember the model
257 must follow the standard rules for model changes and notify the view when
258 the model has changed by using QAbstractItemModel::dataChanged(),
259 QAbstractItemModel::beginInsertRows(), etc. See the \l {Model subclassing reference} for
260 more information.
261
262 The complete example is available in Qt's \l {declarative/modelviews/abstractitemmodel}{examples/declarative/modelviews/abstractitemmodel} directory.
263
264 QAbstractItemModel presents a hierarchy of tables, but the views currently provided by QML
265 can only display list data.
266 In order to display child lists of a hierarchical model
267 the VisualDataModel element provides several properties and functions for use
268 with models of type QAbstractItemModel:
269
270 \list
271 \o \e hasModelChildren role property to determine whether a node has child nodes.
272 \o \l VisualDataModel::rootIndex allows the root node to be specifed
273 \o \l VisualDataModel::modelIndex() returns a QModelIndex which can be assigned to VisualDataModel::rootIndex
274 \o \l VisualDataModel::parentModelIndex() returns a QModelIndex which can be assigned to VisualDataModel::rootIndex
275 \endlist
276
277
278 \section2 Exposing C++ Data Models to QML
279
280 The above examples use QDeclarativeContext::setContextProperty() to set
281 model values directly in QML components. An alternative to this is to
282 register the C++ model class as a QML type from a QML C++ plugin using
283 QDeclarativeExtensionPlugin. This would allow the model classes to be
284 created directly as elements within QML:
285
286 \table
287 \row
288
289 \o
290 \code
291 class MyModelPlugin : public QDeclarativeExtensionPlugin
292 {
293 public:
294     void registerTypes(const char *uri)
295     {
296         qmlRegisterType<MyModel>(uri, 1, 0,
297                 "MyModel");
298     }
299 }
300
301 Q_EXPORT_PLUGIN2(mymodelplugin, MyModelPlugin);
302 \endcode
303
304 \o
305 \qml
306 MyModel {
307     id: myModel
308     ListElement { someProperty: "some value" }
309 }
310 \endqml
311
312 \qml
313 ListView {
314     width: 200; height: 250
315     model: myModel
316     delegate: Text { text: someProperty }
317 }
318 \endqml
319
320 \endtable
321
322 See \l {Tutorial: Writing QML extensions with C++} for details on writing QML C++
323 plugins.
324
325
326
327 \section1 Other Data Models
328
329
330 \section2 An Integer
331
332 An integer can be used to specify a model that contains a certain number
333 of elements. In this case, the model does not have any data roles.
334
335 The following example creates a ListView with five elements:
336 \qml
337 Item {
338     width: 200; height: 250
339
340     Component {
341         id: itemDelegate
342         Text { text: "I am item number: " + index }
343     }
344
345     ListView {
346         anchors.fill: parent
347         model: 5
348         delegate: itemDelegate
349     }
350
351 }
352 \endqml
353
354
355 \section2 An Object Instance
356
357 An object instance can be used to specify a model with a single object element.  The
358 properties of the object are provided as roles.
359
360 The example below creates a list with one item, showing the color of the
361 \e myText text.  Note the use of the fully qualified \e model.color property
362 to avoid clashing with \e color property of the Text element in the delegate.
363
364 \qml
365 Rectangle {
366     width: 200; height: 250
367
368     Text {
369         id: myText
370         text: "Hello"
371         color: "#dd44ee"
372     }
373
374     Component {
375         id: myDelegate
376         Text { text: model.color }
377     }
378
379     ListView {
380         anchors.fill: parent
381         anchors.topMargin: 30
382         model: myText
383         delegate: myDelegate
384     }
385 }
386 \endqml
387
388 \section1 Accessing Views and Models from Delegates
389
390 You can access the view for which a delegate is used, and its
391 properties, by using ListView.view in a delegate on a ListView, or
392 GridView.view in a delegate on a GridView, etc. In particular, you can
393 access the model and its properties by using ListView.view.model.
394
395 This is useful when you want to use the same delegate for a number of
396 views, for example, but you want decorations or other features to be
397 different for each view, and you would like these different settings to
398 be properties of each of the views. Similarly, it might be of interest
399 to access or show some properties of the model.
400
401 In the following example, the delegate shows the property \e{language}
402 of the model, and the color of one of the fields depends on the
403 property \e{fruit_color} of the view.
404
405 \snippet doc/src/snippets/declarative/models/views-models-delegates.qml rectangle
406
407 Another important case is when some action (e.g. mouse click) in the
408 delegate should update data in the model. In this case you can define
409 a function in the model, e.g.:
410
411 \code
412         setData(int row, const QString & field_name, QVariant new_value),
413 \endcode
414
415 ...and call it from the delegate using:
416
417 \js
418         ListView.view.model.setData(index, field, value)
419 \endjs
420
421 ...assuming that \e{field} holds the name of the field which should be
422 updated, and that \e{value} holds the new value.
423
424 */