summaryrefslogtreecommitdiffstats
path: root/doc/src/declarative/qdeclarativemodels.qdoc
blob: b44e6f233fc9a05e17b4b341927fd3312878bb31 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the documentation of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:FDL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in a
** written agreement between you and Nokia.
**
** GNU Free Documentation License
** Alternatively, this file may be used under the terms of the GNU Free
** Documentation License version 1.3 as published by the Free Software
** Foundation and appearing in the file included in the packaging of this
** file.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/

/*!
\page qdeclarativemodels.html
\target qmlmodels
\title Data Models

QML items such as ListView, GridView and \l Repeater require Data Models 
that provide the data to be displayed.
These items typically require a \e delegate component that
creates an instance for each item in the model.  Models may be static, or
have items modified, inserted, removed or moved dynamically.

Data is provided to the delegate via named data roles which the
delegate may bind to. Here is a ListModel with two roles, \e type and \e age,
and a ListView with a delegate that binds to these roles to display their 
values:

\qml
import Qt 4.7

Item {
    width: 200; height: 250

    ListModel {
        id: myModel
        ListElement { type: "Dog"; age: 8 }
        ListElement { type: "Cat"; age: 5 }
    }

    Component {
        id: myDelegate
        Text { text: type + ", " + age }
    }

    ListView {
        anchors.fill: parent
        model: myModel
        delegate: myDelegate
    }
}
\endqml

If there is a naming clash between the model's properties and the delegate's
properties, the roles can be accessed with the qualified \e model name instead.
For example, if a \l Text element had \e type or \e age properties, the text in the
above example would display those property values instead of the \e type and \e age values
from the model item. In this case, the properties could have been referenced as
\c model.type and \c model.age instead to ensure the delegate displays the 
property values from the model item.

A special \e index role containing the index of the item in the model
is also available to the delegate.  Note this index is set to -1 if the item is removed from
the model.  If you bind to the index role, be sure that the logic
accounts for the possibility of index being -1, i.e. that the item
is no longer valid. (Usually the item will shortly be destroyed, but
it is possible to delay delegate destruction in some views via a \c delayRemove
attached property.)

Models that do not have named roles (such as the QStringList model shown below)
will have the data provided via the \e modelData role.  The \e modelData role is also provided for
models that have only one role.  In this case the \e modelData role
contains the same data as the named role.

QML provides several types of data models among the built-in set of
QML elements. In addition, models can be created with C++ and then
made available to QML components.


\section1 QML Data Models

\section2 ListModel

ListModel is a simple hierarchy of elements specified in QML.  The
available roles are specified by the \l ListElement properties.

\code
ListModel {
    id: fruitModel

    ListElement {
        name: "Apple"
        cost: 2.45
    }
    ListElement {
        name: "Orange"
        cost: 3.25
    }
    ListElement {
        name: "Banana"
        cost: 1.95
    }
}
\endcode

The above model has two roles, \e name and \e cost.  These can be bound
to by a ListView delegate, for example:

\code
ListView {
    width: 200; height: 250
    model: fruitModel
    delegate: Row {
        Text { text: "Fruit: " + name }
        Text { text: "Cost: $" + cost }
    }
}
\endcode

ListModel provides methods to manipulate the ListModel directly via JavaScript.
In this case, the first item inserted determines the roles available
to any views that are using the model. For example, if an empty ListModel is
created and populated via JavaScript, the roles provided by the first
insertion are the only roles that will be shown in the view:

\code
Item {
    ListModel { id: fruitModel }

    MouseArea {
        anchors.fill: parent
        onClicked: fruitModel.append({"cost": 5.95, "name":"Pizza"})
    }
}
\endcode

When the MouseArea is clicked, \c fruitModel will have two roles, \e cost and \e name.
Even if subsequent roles are added, only the first two will be handled by views
using the model. To reset the roles available in the model, call ListModel::clear().


\section2 XmlListModel

XmlListModel allows construction of a model from an XML data source. The roles
are specified via the \l XmlRole element.

The following model has three roles, \e title, \e link and \e description:
\code
XmlListModel {
     id: feedModel
     source: "http://rss.news.yahoo.com/rss/oceania"
     query: "/rss/channel/item"
     XmlRole { name: "title"; query: "title/string()" }
     XmlRole { name: "link"; query: "link/string()" }
     XmlRole { name: "description"; query: "description/string()" }
}
\endcode

The \l{demos/declarative/rssnews}{RSS News demo} shows how XmlListModel can
be used to display an RSS feed.


\section2 VisualItemModel

VisualItemModel allows QML items to be provided as a model.  

This model contains both the data and delegate; the child items of a
VisualItemModel provide the contents of the delegate. The model 
does not provide any roles.

\code
 VisualItemModel {
     id: itemModel
     Rectangle { height: 30; width: 80; color: "red" }
     Rectangle { height: 30; width: 80; color: "green" }
     Rectangle { height: 30; width: 80; color: "blue" }
 }

 ListView {
     anchors.fill: parent
     model: itemModel
 }
\endcode

Note that in the above example there is no delegate required.
The items of the model itself provide the visual elements that
will be positioned by the view.


\section1 C++ Data Models

Models can be defined in C++ and then made available to QML. This is useful
for exposing existing C++ data models or otherwise complex datasets to QML.

A C++ model class can be defined as a QStringList, a QList<QObject*> or a
QAbstractItemModel. 

\section2 QStringList

A model may be a simple QStringList, which provides the contents of the list via the \e modelData role.

Here is a ListView with a delegate that references its model item's 
value using the \c modelData role:

\snippet examples/declarative/modelviews/stringlistmodel/view.qml 0

A Qt application can load this QML document and set the value of \c myModel
to a QStringList:

\snippet examples/declarative/modelviews/stringlistmodel/main.cpp 0

The complete example is available in Qt's \l {declarative/modelviews/stringlistmodel}{examples/declarative/modelviews/stringlistmodel} directory.

\note There is no way for the view to know that the contents of a QStringList
have changed.  If the QStringList changes, it will be necessary to reset
the model by calling QDeclarativeContext::setContextProperty() again.


\section2 QList<QObject*>

A list of QObject* values can also be used as a model. A QList<QObject*> provides 
the properties of the objects in the list as roles.

The following application creates a \c DataObject class that with
Q_PROPERTY values that will be accessible as named roles when a
QList<DataObject*> is exposed to QML:

\snippet examples/declarative/modelviews/objectlistmodel/dataobject.h 0
\dots 4
\snippet examples/declarative/modelviews/objectlistmodel/dataobject.h 1
\codeline
\snippet examples/declarative/modelviews/objectlistmodel/main.cpp 0
\dots

The QObject* is available as the \c modelData property.  As a convenience,
the properties of the object are also made available directly in the
delegate's context. Here, \c view.qml references the \c DataModel properties in
the ListView delegate:

\snippet examples/declarative/modelviews/objectlistmodel/view.qml 0

Note the use of the fully qualified access to the \c color property.  
The properties of the object are not replicated in the \c model
object, since they are easily available via the \c modelData
object.

The complete example is available in Qt's \l {declarative/modelviews/objectlistmodel}{examples/declarative/modelviews/objectlistmodel} directory.

Note: There is no way for the view to know that the contents of a QList
have changed.  If the QList changes, it will be necessary to reset
the model by calling QDeclarativeContext::setContextProperty() again.


\section2 QAbstractItemModel

A model can be defined by subclassing QAbstractItemModel.

The roles of a QAbstractItemModel subclass can be exposed to QML by calling 
QAbstractItemModel::setRoleNames(). The default role names set by Qt are:

\table
\header
\o Qt Role
\o QML Role Name
\row
\o Qt::DisplayRole
\o display
\row
\o Qt::DecorationRole
\o decoration
\endtable

Here is an application with a QAbstractListModel subclass named \c AnimalModel
that has \e type and \e size roles. It calls QAbstractItemModel::setRoleNames() to set the
role names for accessing the properties via QML:

\snippet examples/declarative/modelviews/abstractitemmodel/model.h 0
\dots 
\snippet examples/declarative/modelviews/abstractitemmodel/model.h 1
\dots 
\snippet examples/declarative/modelviews/abstractitemmodel/model.h 2
\codeline
\snippet examples/declarative/modelviews/abstractitemmodel/model.cpp 0
\codeline
\snippet examples/declarative/modelviews/abstractitemmodel/main.cpp 0
\dots

This model is displayed by a ListView delegate that accesses the \e type and \e size
roles:

\snippet examples/declarative/modelviews/abstractitemmodel/view.qml 0

The complete example is available in Qt's \l {declarative/modelviews/abstractitemmodel}{examples/declarative/modelviews/abstractitemmodel} directory.

QAbstractItemModel presents a hierarchy of tables, but the views currently provided by QML
can only display list data.  
In order to display child lists of a hierarchical model
the VisualDataModel element provides several properties and functions for use
with models of type QAbstractItemModel:

\list
\o \e hasModelChildren role property to determine whether a node has child nodes.
\o \l VisualDataModel::rootIndex allows the root node to be specifed
\o \l VisualDataModel::modelIndex() returns a QModelIndex which can be assigned to VisualDataModel::rootIndex
\o \l VisualDataModel::parentModelIndex() returns a QModelIndex which can be assigned to VisualDataModel::rootIndex
\endlist


\section2 Exposing C++ data models to QML

The above examples use QDeclarativeContext::setContextProperty() to set 
model values directly in QML components. An alternative to this is to 
register the C++ model class as a QML type from a QML C++ plugin using 
QDeclarativeExtensionPlugin. This would allow the model classes to be 
created directly as elements within QML:

\table
\row 

\o
\code
class MyModelPlugin : public QDeclarativeExtensionPlugin
{
public:
    void registerTypes(const char *uri)
    {
        qmlRegisterType<MyModel>(uri, 1, 0, 
                "MyModel");
    }
}

Q_EXPORT_PLUGIN2(mymodelplugin, MyModelPlugin);
\endcode

\o
\qml
MyModel {
    id: myModel
    ListElement { someProperty: "some value" }
}

ListView {
    width: 200; height: 250
    model: myModel
    delegate: Text { text: someProperty }
}
\endqml

\endtable

See \l {Tutorial: Writing QML extensions with C++} for details on writing QML C++
plugins.



\section1 Other Data Models


\section2 An Integer

An integer can be used to specify a model that contains a certain number
of elements. In this case, the model does not have any data roles.

The following example creates a ListView with five elements:
\code
Item {
    width: 200; height: 250

    Component {
        id: itemDelegate
        Text { text: "I am item number: " + index }
    }

    ListView {
        anchors.fill: parent
        model: 5
        delegate: itemDelegate
    }

}
\endcode


\section2 An Object Instance

An object instance can be used to specify a model with a single object element.  The
properties of the object are provided as roles.

The example below creates a list with one item, showing the color of the
\e myText text.  Note the use of the fully qualified \e model.color property
to avoid clashing with \e color property of the Text element in the delegate.

\code
Rectangle {
    width: 200; height: 250

    Text {
        id: myText
        text: "Hello"
        color: "#dd44ee"
    }

    Component {
        id: myDelegate
        Text { text: model.color }
    }

    ListView {
        anchors.fill: parent
        anchors.topMargin: 30
        model: myText
        delegate: myDelegate
    }
}
\endcode

*/