source: trunk/doc/src/declarative/qdeclarativemodels.qdoc@ 846

Last change on this file since 846 was 846, checked in by Dmitry A. Kuminov, 14 years ago

trunk: Merged in qt 4.7.2 sources from branches/vendor/nokia/qt.

File size: 17.8 KB
Line 
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** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in a
14** written agreement between you and Nokia.
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\target qmlmodels
31\title QML Data Models
32
33QML items such as ListView, GridView and \l Repeater require Data Models
34that provide the data to be displayed.
35These items typically require a \e delegate component that
36creates an instance for each item in the model. Models may be static, or
37have items modified, inserted, removed or moved dynamically.
38
39Data is provided to the delegate via named data roles which the
40delegate may bind to. Here is a ListModel with two roles, \e type and \e age,
41and a ListView with a delegate that binds to these roles to display their
42values:
43
44\snippet doc/src/snippets/declarative/qml-data-models/listmodel-listview.qml document
45
46If there is a naming clash between the model's properties and the delegate's
47properties, the roles can be accessed with the qualified \e model name instead.
48For example, if a \l Text element had \e type or \e age properties, the text in the
49above example would display those property values instead of the \e type and \e age values
50from the model item. In this case, the properties could have been referenced as
51\c model.type and \c model.age instead to ensure the delegate displays the
52property values from the model item.
53
54A special \e index role containing the index of the item in the model
55is also available to the delegate. Note this index is set to -1 if the item is removed from
56the model. If you bind to the index role, be sure that the logic
57accounts for the possibility of index being -1, i.e. that the item
58is no longer valid. (Usually the item will shortly be destroyed, but
59it is possible to delay delegate destruction in some views via a \c delayRemove
60attached property.)
61
62Models that do not have named roles (such as the QStringList model shown below)
63will have the data provided via the \e modelData role. The \e modelData role is also provided for
64models that have only one role. In this case the \e modelData role
65contains the same data as the named role.
66
67QML provides several types of data models among the built-in set of
68QML elements. In addition, models can be created with C++ and then
69made available to QML components.
70
71The views used to access data models are described in \l{Presenting Data with QML}.
72The use of positioner items to arrange items from a model is covered in
73\l{Using QML Positioner and Repeater Items}.
74
75
76\section1 QML Data Models
77
78\section2 ListModel
79
80ListModel is a simple hierarchy of elements specified in QML. The
81available roles are specified by the \l ListElement properties.
82
83\snippet doc/src/snippets/declarative/qml-data-models/listelements.qml model
84
85The above model has two roles, \e name and \e cost. These can be bound
86to by a ListView delegate, for example:
87
88\snippet doc/src/snippets/declarative/qml-data-models/listelements.qml view
89
90ListModel provides methods to manipulate the ListModel directly via JavaScript.
91In this case, the first item inserted determines the roles available
92to any views that are using the model. For example, if an empty ListModel is
93created and populated via JavaScript, the roles provided by the first
94insertion are the only roles that will be shown in the view:
95
96\snippet doc/src/snippets/declarative/qml-data-models/dynamic-listmodel.qml model
97\dots
98\snippet doc/src/snippets/declarative/qml-data-models/dynamic-listmodel.qml mouse area
99
100When the MouseArea is clicked, \c fruitModel will have two roles, \e cost and \e name.
101Even if subsequent roles are added, only the first two will be handled by views
102using the model. To reset the roles available in the model, call ListModel::clear().
103
104
105\section2 XmlListModel
106
107XmlListModel allows construction of a model from an XML data source. The roles
108are specified via the \l XmlRole element.
109
110The following model has three roles, \e title, \e link and \e description:
111\code
112XmlListModel {
113 id: feedModel
114 source: "http://rss.news.yahoo.com/rss/oceania"
115 query: "/rss/channel/item"
116 XmlRole { name: "title"; query: "title/string()" }
117 XmlRole { name: "link"; query: "link/string()" }
118 XmlRole { name: "description"; query: "description/string()" }
119}
120\endcode
121
122The \l{demos/declarative/rssnews}{RSS News demo} shows how XmlListModel can
123be used to display an RSS feed.
124
125
126\section2 VisualItemModel
127
128VisualItemModel allows QML items to be provided as a model.
129
130This model contains both the data and delegate; the child items of a
131VisualItemModel provide the contents of the delegate. The model
132does not provide any roles.
133
134\code
135 VisualItemModel {
136 id: itemModel
137 Rectangle { height: 30; width: 80; color: "red" }
138 Rectangle { height: 30; width: 80; color: "green" }
139 Rectangle { height: 30; width: 80; color: "blue" }
140 }
141
142 ListView {
143 anchors.fill: parent
144 model: itemModel
145 }
146\endcode
147
148Note that in the above example there is no delegate required.
149The items of the model itself provide the visual elements that
150will be positioned by the view.
151
152
153\section1 C++ Data Models
154
155Models can be defined in C++ and then made available to QML. This is useful
156for exposing existing C++ data models or otherwise complex datasets to QML.
157
158A C++ model class can be defined as a QStringList, a QList<QObject*> or a
159QAbstractItemModel. The first two are useful for exposing simpler datasets,
160while QAbstractItemModel provides a more flexible solution for more complex
161models.
162
163
164\section2 QStringList
165
166A model may be a simple QStringList, which provides the contents of the list via the \e modelData role.
167
168Here is a ListView with a delegate that references its model item's
169value using the \c modelData role:
170
171\snippet examples/declarative/modelviews/stringlistmodel/view.qml 0
172
173A Qt application can load this QML document and set the value of \c myModel
174to a QStringList:
175
176\snippet examples/declarative/modelviews/stringlistmodel/main.cpp 0
177
178The complete example is available in Qt's \l {declarative/modelviews/stringlistmodel}{examples/declarative/modelviews/stringlistmodel} directory.
179
180\note There is no way for the view to know that the contents of a QStringList
181have changed. If the QStringList changes, it will be necessary to reset
182the model by calling QDeclarativeContext::setContextProperty() again.
183
184
185\section2 QList<QObject*>
186
187A list of QObject* values can also be used as a model. A QList<QObject*> provides
188the properties of the objects in the list as roles.
189
190The following application creates a \c DataObject class that with
191Q_PROPERTY values that will be accessible as named roles when a
192QList<DataObject*> is exposed to QML:
193
194\snippet examples/declarative/modelviews/objectlistmodel/dataobject.h 0
195\dots 4
196\snippet examples/declarative/modelviews/objectlistmodel/dataobject.h 1
197\codeline
198\snippet examples/declarative/modelviews/objectlistmodel/main.cpp 0
199\dots
200
201The QObject* is available as the \c modelData property. As a convenience,
202the properties of the object are also made available directly in the
203delegate's context. Here, \c view.qml references the \c DataModel properties in
204the ListView delegate:
205
206\snippet examples/declarative/modelviews/objectlistmodel/view.qml 0
207
208Note the use of the fully qualified access to the \c color property.
209The properties of the object are not replicated in the \c model
210object, since they are easily available via the \c modelData
211object.
212
213The complete example is available in Qt's \l {declarative/modelviews/objectlistmodel}{examples/declarative/modelviews/objectlistmodel} directory.
214
215Note: There is no way for the view to know that the contents of a QList
216have changed. If the QList changes, it will be necessary to reset
217the model by calling QDeclarativeContext::setContextProperty() again.
218
219
220\section2 QAbstractItemModel
221
222A model can be defined by subclassing QAbstractItemModel. This is the
223best approach if you have a more complex model that cannot be supported
224by the other approaches. A QAbstractItemModel can also automatically
225notify a QML view when the model data has changed.
226
227The roles of a QAbstractItemModel subclass can be exposed to QML by calling
228QAbstractItemModel::setRoleNames(). The default role names set by Qt are:
229
230\table
231\header
232\o Qt Role
233\o QML Role Name
234\row
235\o Qt::DisplayRole
236\o display
237\row
238\o Qt::DecorationRole
239\o decoration
240\endtable
241
242Here is an application with a QAbstractListModel subclass named \c AnimalModel
243that has \e type and \e size roles. It calls QAbstractItemModel::setRoleNames() to set the
244role names for accessing the properties via QML:
245
246\snippet examples/declarative/modelviews/abstractitemmodel/model.h 0
247\dots
248\snippet examples/declarative/modelviews/abstractitemmodel/model.h 1
249\dots
250\snippet examples/declarative/modelviews/abstractitemmodel/model.h 2
251\codeline
252\snippet examples/declarative/modelviews/abstractitemmodel/model.cpp 0
253\codeline
254\snippet examples/declarative/modelviews/abstractitemmodel/main.cpp 0
255\dots
256
257This model is displayed by a ListView delegate that accesses the \e type and \e size
258roles:
259
260\snippet examples/declarative/modelviews/abstractitemmodel/view.qml 0
261
262QML views are automatically updated when the model changes. Remember the model
263must follow the standard rules for model changes and notify the view when
264the model has changed by using QAbstractItemModel::dataChanged(),
265QAbstractItemModel::beginInsertRows(), etc. See the \l {Model subclassing reference} for
266more information.
267
268The complete example is available in Qt's \l {declarative/modelviews/abstractitemmodel}{examples/declarative/modelviews/abstractitemmodel} directory.
269
270QAbstractItemModel presents a hierarchy of tables, but the views currently provided by QML
271can only display list data.
272In order to display child lists of a hierarchical model
273the VisualDataModel element provides several properties and functions for use
274with models of type QAbstractItemModel:
275
276\list
277\o \e hasModelChildren role property to determine whether a node has child nodes.
278\o \l VisualDataModel::rootIndex allows the root node to be specifed
279\o \l VisualDataModel::modelIndex() returns a QModelIndex which can be assigned to VisualDataModel::rootIndex
280\o \l VisualDataModel::parentModelIndex() returns a QModelIndex which can be assigned to VisualDataModel::rootIndex
281\endlist
282
283
284\section2 Exposing C++ data models to QML
285
286The above examples use QDeclarativeContext::setContextProperty() to set
287model values directly in QML components. An alternative to this is to
288register the C++ model class as a QML type from a QML C++ plugin using
289QDeclarativeExtensionPlugin. This would allow the model classes to be
290created directly as elements within QML:
291
292\table
293\row
294
295\o
296\code
297class MyModelPlugin : public QDeclarativeExtensionPlugin
298{
299public:
300 void registerTypes(const char *uri)
301 {
302 qmlRegisterType<MyModel>(uri, 1, 0,
303 "MyModel");
304 }
305}
306
307Q_EXPORT_PLUGIN2(mymodelplugin, MyModelPlugin);
308\endcode
309
310\o
311\qml
312MyModel {
313 id: myModel
314 ListElement { someProperty: "some value" }
315}
316
317ListView {
318 width: 200; height: 250
319 model: myModel
320 delegate: Text { text: someProperty }
321}
322\endqml
323
324\endtable
325
326See \l {Tutorial: Writing QML extensions with C++} for details on writing QML C++
327plugins.
328
329
330
331\section1 Other Data Models
332
333
334\section2 An Integer
335
336An integer can be used to specify a model that contains a certain number
337of elements. In this case, the model does not have any data roles.
338
339The following example creates a ListView with five elements:
340\code
341Item {
342 width: 200; height: 250
343
344 Component {
345 id: itemDelegate
346 Text { text: "I am item number: " + index }
347 }
348
349 ListView {
350 anchors.fill: parent
351 model: 5
352 delegate: itemDelegate
353 }
354
355}
356\endcode
357
358
359\section2 An Object Instance
360
361An object instance can be used to specify a model with a single object element. The
362properties of the object are provided as roles.
363
364The example below creates a list with one item, showing the color of the
365\e myText text. Note the use of the fully qualified \e model.color property
366to avoid clashing with \e color property of the Text element in the delegate.
367
368\code
369Rectangle {
370 width: 200; height: 250
371
372 Text {
373 id: myText
374 text: "Hello"
375 color: "#dd44ee"
376 }
377
378 Component {
379 id: myDelegate
380 Text { text: model.color }
381 }
382
383 ListView {
384 anchors.fill: parent
385 anchors.topMargin: 30
386 model: myText
387 delegate: myDelegate
388 }
389}
390\endcode
391
392\section1 Accessing Views and Models from Delegates
393
394You can access the view for which a delegate is used, and its
395properties, by using ListView.view in a delegate on a ListView, or
396GridView.view in a delegate on a GridView, etc. In particular, you can
397access the model and its properties by using ListView.view.model.
398
399This is useful when you want to use the same delegate for a number of
400views, for example, but you want decorations or other features to be
401different for each view, and you would like these different settings to
402be properties of each of the views. Similarly, it might be of interest
403to access or show some properties of the model.
404
405In the following example, the delegate shows the property \e{language}
406of the model, and the color of one of the fields depends on the
407property \e{fruit_color} of the view.
408
409\code
410Rectangle {
411 width: 200; height: 200
412
413 ListModel {
414 id: fruitModel
415 property string language: "en"
416 ListElement {
417 name: "Apple"
418 cost: 2.45
419 }
420 ListElement {
421 name: "Orange"
422 cost: 3.25
423 }
424 ListElement {
425 name: "Banana"
426 cost: 1.95
427 }
428 }
429
430 Component {
431 id: fruitDelegate
432 Row {
433 Text { text: " Fruit: " + name; color: ListView.view.fruit_color }
434 Text { text: " Cost: $" + cost }
435 Text { text: " Language: " + ListView.view.model.language }
436 }
437 }
438
439 ListView {
440 property color fruit_color: "green"
441 model: fruitModel
442 delegate: fruitDelegate
443 anchors.fill: parent
444 }
445}
446\endcode
447
448Another important case is when some action (e.g. mouse click) in the
449delegate should update data in the model. In this case you can define
450a function in the model, e.g.:
451
452\code
453 setData(int row, const QString & field_name, QVariant new_value),
454\endcode
455
456...and call it from the delegate using:
457
458\code
459 ListView.view.model.setData(index, field, value)
460\endcode
461
462...assuming that \e{field} holds the name of the field which should be
463updated, and that \e{value} holds the new value.
464
465*/
466
467/*!
468\page qml-presenting-data.html
469\title Presenting Data with QML
470
471\section1 Introduction
472
473Qt Quick contains a set of standard items that can be used to present data in a
474number of different ways. For simple user interfaces,
475\l{Using QML Positioner and Repeater Items#Repeaters}{Repeaters} can be used
476in combination with
477\l{Using QML Positioner and Repeater Items#Positioners}{Positioners}
478to obtain pieces of data and arrange them in a user interface. However, when
479large quantities of data are involved, it is often better to use models with
480the standard views since these contain many built-in display and navigation
481features.
482
483\section1 Views
484
485Views are scrolling containers for collections of items. They are feature-rich,
486supporting many of the use cases found in typical applications, and can be
487customized to meet requirements on style and behavior.
488
489A set of standard views are provided in the basic set of Qt Quick
490graphical elements:
491
492\list
493\o \l{#ListView}{ListView} arranges items in a horizontal or vertical list
494\o \l{#GridView}{GridView} arranges items in a grid within the available space
495\o \l{#PathView}{PathView} arranges items on a path
496\endlist
497
498Unlike these items, \l WebView is not a fully-featured view item, and needs
499to be combined with a \l Flickable item to create a view that performs like
500a Web browser.
501
502\section2 ListView
503
504\l ListView shows a classic list of items with horizontal or vertical placing
505of items.
506
507\beginfloatright
508\inlineimage qml-listview-snippet.png
509\endfloat
510
511The following example shows a minimal ListView displaying a sequence of
512numbers (using an \l{QML Data Models#An Integer}{integer as a model}).
513A simple delegate is used to define an items for each piece of data in the
514model.
515
516\clearfloat
517\snippet doc/src/snippets/declarative/listview/listview-snippet.qml document
518
519
520
521\section2 GridView
522
523\l GridView displays items in a grid like an file manager's icon view.
524
525\section2 PathView
526
527\l PathView displays items on a path, where the selection remains in
528the same place and the items move around it.
529
530\section1 Decorating Views
531
532\section2 Headers and Footers
533
534\section2 Sections
535
536\section2 Navigation
537
538In traditional user interfaces, views can be scrolled using standard
539controls, such as scroll bars and arrow buttons. In some situations, it
540is also possible to drag the view directly by pressing and holding a
541mouse button while moving the cursor. In touch-based user interfaces,
542this dragging action is often complemented with a flicking action, where
543scrolling continues after the user has stopped touching the view.
544
545\section1 Further Reading
546*/
Note: See TracBrowser for help on using the repository browser.