Making trivial snippets inline
[profile/ivi/qtbase.git] / examples / widgets / doc / editabletreemodel.qdoc
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
5 **
6 ** This file is part of the documentation of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:FDL$
9 ** GNU Free Documentation License
10 ** Alternatively, this file may be used under the terms of the GNU Free
11 ** Documentation License version 1.3 as published by the Free Software
12 ** Foundation and appearing in the file included in the packaging of
13 ** this file.
14 **
15 ** Other Usage
16 ** Alternatively, this file may be used in accordance with the terms
17 ** and conditions contained in a signed written agreement between you
18 ** and Nokia.
19 **
20 **
21 **
22 **
23 **
24 ** $QT_END_LICENSE$
25 **
26 ****************************************************************************/
27
28 /*!
29     \example itemviews/editabletreemodel
30     \title Editable Tree Model Example
31
32     This example shows how to implement a simple item-based tree model that can
33     be used with other classes the model/view framework.
34
35     \image itemviews-editabletreemodel.png
36
37     The model supports editable items, custom headers, and the ability to
38     insert and remove rows and columns. With these features, it is also
39     possible to insert new child items, and this is shown in the supporting
40     example code.
41
42     \note The model only shows the basic principles used when creating an
43     editable, hierarchical model. You may wish to use the \l{ModelTest}
44     project to test production models.
45
46     \section1 Overview
47
48     As described in the \l{Model Subclassing Reference}, models must
49     provide implementations for the standard set of model functions:
50     \l{QAbstractItemModel::}{flags()}, \l{QAbstractItemModel::}{data()},
51     \l{QAbstractItemModel::}{headerData()},
52     \l{QAbstractItemModel::}{columnCount()}, and
53     \l{QAbstractItemModel::}{rowCount()}. In addition, hierarchical models,
54     such as this one, need to provide implementations of
55     \l{QAbstractItemModel::}{index()} and \l{QAbstractItemModel::}{parent()}.
56
57     An editable model needs to provide implementations of
58     \l{QAbstractItemModel::}{setData()} and
59     \l{QAbstractItemModel::}{setHeaderData()}, and must return a suitable
60     combination of flags from its \l{QAbstractItemModel::}{flags()} function.
61
62     Since this example allows the dimensions of the model to be changed,
63     we must also implement \l{QAbstractItemModel::}{insertRows()},
64     \l{QAbstractItemModel::}{insertColumns()},
65     \l{QAbstractItemModel::}{removeRows()}, and
66     \l{QAbstractItemModel::}{removeColumns()}.
67
68     \section1 Design
69
70     As with the \l{itemviews/simpletreemodel}{Simple Tree Model} example,
71     the model simply acts as a wrapper around a collection
72     of instances of a \c TreeItem class. Each \c TreeItem is designed to
73     hold data for a row of items in a tree view, so it contains a list of
74     values corresponding to the data shown in each column.
75
76     Since QTreeView provides a row-oriented view onto a model, it is
77     natural to choose a row-oriented design for data structures that
78     will supply data via a model to this kind of view. Although this makes
79     the tree model less flexible, and possibly less useful for use with
80     more sophisticated views, it makes it less complex to design and easier
81     to implement.
82
83     \target Relations-between-internal-items
84     \table
85     \row \li \inlineimage itemviews-editabletreemodel-items.png
86     \li \b{Relations between internal items}
87
88     When designing a data structure for use with a custom model, it is useful
89     to expose each item's parent via a function like
90     \l{TreeItem::parent}{TreeItem::parent()} because it will make
91     writing the model's own \l{QAbstractItemModel::}{parent()} function easier.
92     Similarly, a function like \l{TreeItem::child}{TreeItem::child()} is
93     helpful when implementing the model's \l{QAbstractItemModel::}{index()}
94     function. As a result, each \c TreeItem maintains information about
95     its parent and children, making it possible for us to traverse the tree
96     structure.
97
98     The diagram shows how \c TreeItem instances are connected via their
99     \l{TreeItem::parent}{parent()} and \l{TreeItem::child}{child()}
100     functions.
101
102     In the example shown, two top-level items, \b{A} and
103     \b{B}, can be obtained from the root item by calling its child()
104     function, and each of these items return the root node from their
105     parent() functions, though this is only shown for item \b{A}.
106     \endtable
107
108     Each \c TreeItem stores data for each column in the row it represents
109     in its \c itemData private member (a list of QVariant objects).
110     Since there is a one-to-one mapping between each column in the view
111     and each entry in the list, we provide a simple
112     \l{TreeItem::data}{data()} function to read entries in the \c itemData
113     list and a \l{TreeItem::setData}{setData()} function to allow them to
114     be modified.
115     As with other functions in the item, this simplifies the implemention
116     of the model's \l{QAbstractItemModel::}{data()} and
117     \l{QAbstractItemModel::}{setData()} functions.
118
119     We place an item at the root of the tree of items. This root item
120     corresponds to the null model index, \l{QModelIndex::}{QModelIndex()},
121     that is used to represent the parent of a top-level item when handling
122     model indexes.
123     Although the root item does not have a visible representation in any of
124     the standard views, we use its internal list of QVariant objects to
125     store a list of strings that will be passed to views for use as
126     horizontal header titles.
127
128     \table
129     \row \li \inlineimage itemviews-editabletreemodel-model.png
130     \li \b{Accessing data via the model}
131
132     In the case shown in the diagram, the piece of information represented
133     by \b{a} can be obtained using the standard model/view API:
134
135     \code
136     QVariant a = model->index(0, 0, QModelIndex()).data();
137     \endcode
138
139     Since each items holds pieces of data for each column in a given row,
140     there can be many model indexes that map to the same \c TreeItem object.
141     For example, the information represented by \b{b} can be obtained
142     using the following code:
143
144     \code
145     QVariant b = model->index(1, 0, QModelIndex()).data();
146     \endcode
147
148     The same underlying \c TreeItem would be accessed to obtain information
149     for the other model indexes in the same row as \b{b}.
150     \endtable
151
152     In the model class, \c TreeModel, we relate \c TreeItem objects to
153     model indexes by passing a pointer for each item when we create its
154     corresponding model index with QAbstractItemModel::createIndex() in
155     our \l{TreeModel::index}{index()} and \l{TreeModel::parent}{parent()}
156     implementations.
157     We can retrieve pointers stored in this way by calling the
158     \l{QModelIndex::}{internalPointer()} function on the relevant model
159     index - we create our own \l{TreeModel::getItem}{getItem()} function to
160     do this work for us, and call it from our \l{TreeModel::data}{data()}
161     and \l{TreeModel::parent}{parent()} implementations.
162
163     Storing pointers to items is convenient when we control how they are
164     created and destroyed since we can assume that an address obtained from
165     \l{QModelIndex::}{internalPointer()} is a valid pointer.
166     However, some models need to handle items that are obtained from other
167     components in a system, and in many cases it is not possible to fully
168     control how items are created or destroyed. In such situations, a pure
169     pointer-based approach needs to be supplemented by safeguards to ensure
170     that the model does not attempt to access items that have been deleted.
171
172     \table
173     \row \li \b{Storing information in the underlying data structure}
174
175     Several pieces of data are stored as QVariant objects in the \c itemData
176     member of each \c TreeItem instance
177
178     The diagram shows how pieces of information,
179     represented by the labels \b{a}, \b{b} and \b{c} in the
180     previous two diagrams, are stored in items \b{A}, \b{B} and
181     \b{C} in the underlying data structure. Note that pieces of
182     information from the same row in the model are all obtained from the
183     same item. Each element in a list corresponds to a piece of information
184     exposed by each column in a given row in the model.
185
186     \li \inlineimage itemviews-editabletreemodel-values.png
187     \endtable
188
189     Since the \c TreeModel implementation has been designed for use with
190     QTreeView, we have added a restriction on the way it uses \c TreeItem
191     instances: each item must expose the same number of columns of data.
192     This makes viewing the model consistent, allowing us to use the root
193     item to determine the number of columns for any given row, and only
194     adds the requirement that we create items containing enough data for
195     the total number of columns. As a result, inserting and removing
196     columns are time-consuming operations because we need to traverse the
197     entire tree to modify every item.
198
199     An alternative approach would be to design the \c TreeModel class so
200     that it truncates or expands the list of data in individual \c TreeItem
201     instances as items of data are modified. However, this "lazy" resizing
202     approach would only allow us to insert and remove columns at the end of
203     each row and would not allow columns to be inserted or removed at
204     arbitrary positions in each row.
205
206     \target Relating-items-using-model-indexes
207     \table
208     \row
209     \li \inlineimage itemviews-editabletreemodel-indexes.png
210     \li \b{Relating items using model indexes}
211
212     As with the \l{itemviews/simpletreemodel}{Simple Tree Model} example,
213     the \c TreeModel needs to be able to take a model index, find the
214     corresponding \c TreeItem, and return model indexes that correspond to
215     its parents and children. 
216
217     In the diagram, we show how the model's \l{TreeModel::parent}{parent()}
218     implementation obtains the model index corresponding to the parent of
219     an item supplied by the caller, using the items shown in a
220     \l{Relations-between-internal-items}{previous diagram}.
221
222     A pointer to item \b{C} is obtained from the corresponding model index
223     using the \l{QModelIndex::internalPointer()} function. The pointer was
224     stored internally in the index when it was created. Since the child
225     contains a pointer to its parent, we use its \l{TreeItem::parent}{parent()}
226     function to obtain a pointer to item \b{B}. The parent model index is
227     created using the QAbstractItemModel::createIndex() function, passing
228     the pointer to item \b{B} as the internal pointer.
229     \endtable
230
231     \section1 TreeItem Class Definition
232
233     The \c TreeItem class provides simple items that contain several
234     pieces of data, and which can provide information about their parent
235     and child items:
236
237     \snippet itemviews/editabletreemodel/treeitem.h 0
238
239     We have designed the API to be similar to that provided by
240     QAbstractItemModel by giving each item functions to return the number
241     of columns of information, read and write data, and insert and remove
242     columns. However, we make the relationship between items explicit by
243     providing functions to deal with "children" rather than "rows".
244
245     Each item contains a list of pointers to child items, a pointer to its
246     parent item, and a list of QVariant objects that correspond to
247     information held in columns in a given row in the model.
248
249     \section1 TreeItem Class Implementation
250
251     Each \c TreeItem is constructed with a list of data and an optional
252     parent item:
253
254     \snippet itemviews/editabletreemodel/treeitem.cpp 0
255
256     Initially, each item has no children. These are added to the item's
257     internal \c childItems member using the \c insertChildren() function
258     described later.
259
260     The destructor ensures that each child added to the item is deleted
261     when the item itself is deleted:
262
263     \snippet itemviews/editabletreemodel/treeitem.cpp 1
264
265     \target TreeItem::parent
266     Since each item stores a pointer to its parent, the \c parent() function
267     is trivial:
268
269     \snippet itemviews/editabletreemodel/treeitem.cpp 9
270
271     \target TreeItem::child
272     Three functions provide information about the children of an item.
273     \c child() returns a specific child from the internal list of children:
274
275     \snippet itemviews/editabletreemodel/treeitem.cpp 2
276
277     The \c childCount() function returns the total number of children:
278
279     \snippet itemviews/editabletreemodel/treeitem.cpp 3
280
281     The \c childNumber() function is used to determine the index of the child
282     in its parent's list of children. It accesses the parent's \c childItems
283     member directly to obtain this information:
284
285     \snippet itemviews/editabletreemodel/treeitem.cpp 4
286
287     The root item has no parent item; for this item, we return zero to be
288     consistent with the other items.
289
290     The \c columnCount() function simply returns the number of elements in
291     the internal \c itemData list of QVariant objects:
292
293     \snippet itemviews/editabletreemodel/treeitem.cpp 5
294
295     \target TreeItem::data
296     Data is retrieved using the \c data() function, which accesses the
297     appropriate element in the \c itemData list:
298
299     \snippet itemviews/editabletreemodel/treeitem.cpp 6
300
301     \target TreeItem::setData
302     Data is set using the \c setData() function, which only stores values
303     in the \c itemData list for valid list indexes, corresponding to column
304     values in the model:
305
306     \snippet itemviews/editabletreemodel/treeitem.cpp 11
307
308     To make implementation of the model easier, we return true to indicate
309     whether the data was set successfully, or false if an invalid column
310
311     Editable models often need to be resizable, enabling rows and columns to
312     be inserted and removed. The insertion of rows beneath a given model index
313     in the model leads to the insertion of new child items in the corresponding
314     item, handled by the \c insertChildren() function:
315
316     \snippet itemviews/editabletreemodel/treeitem.cpp 7
317
318     This ensures that new items are created with the required number of columns
319     and inserted at a valid position in the internal \c childItems list.
320     Items are removed with the \c removeChildren() function:
321
322     \snippet itemviews/editabletreemodel/treeitem.cpp 10
323
324     As discussed above, the functions for inserting and removing columns are
325     used differently to those for inserting and removing child items because
326     they are expected to be called on every item in the tree. We do this by
327     recursively calling this function on each child of the item:
328
329     \snippet itemviews/editabletreemodel/treeitem.cpp 8
330
331     \section1 TreeModel Class Definition
332
333     The \c TreeModel class provides an implementation of the QAbstractItemModel
334     class, exposing the necessary interface for a model that can be edited and
335     resized.
336
337     \snippet itemviews/editabletreemodel/treemodel.h 0
338
339     The constructor and destructor are specific to this model.
340
341     \snippet itemviews/editabletreemodel/treemodel.h 1
342
343     Read-only tree models only need to provide the above functions. The
344     following public functions provide support for editing and resizing:
345
346     \snippet itemviews/editabletreemodel/treemodel.h 2
347
348     To simplify this example, the data exposed by the model is organized into
349     a data structure by the model's \l{TreeModel::setupModelData}{setupModelData()}
350     function. Many real world models will not process the raw data at all, but
351     simply work with an existing data structure or library API.
352
353     \section1 TreeModel Class Implementation
354
355     The constructor creates a root item and initializes it with the header
356     data supplied:
357
358     \snippet itemviews/editabletreemodel/treemodel.cpp 0
359
360     We call the internal \l{TreeModel::setupModelData}{setupModelData()}
361     function to convert the textual data supplied to a data structure we can
362     use with the model. Other models may be initialized with a ready-made
363     data structure, or use an API to a library that maintains its own data.
364
365     The destructor only has to delete the root item; all child items will
366     be recursively deleted by the \c TreeItem destructor.
367
368     \snippet itemviews/editabletreemodel/treemodel.cpp 1
369
370     \target TreeModel::getItem
371     Since the model's interface to the other model/view components is based
372     on model indexes, and the internal data structure is item-based, many of
373     the functions implemented by the model need to be able to convert any
374     given model index to its corresponding item. For convenience and
375     consistency, we have defined a \c getItem() function to perform this
376     repetitive task:
377
378     \snippet itemviews/editabletreemodel/treemodel.cpp 4
379
380     This function assumes that each model index it is passed corresponds to
381     a valid item in memory. If the index is invalid, or its internal pointer
382     does not refer to a valid item, the root item is returned instead.
383
384     The model's \c rowCount() implementation is simple: it first uses the
385     \c getItem() function to obtain the relevant item, then returns the
386     number of children it contains:
387
388     \snippet itemviews/editabletreemodel/treemodel.cpp 8
389
390     By contrast, the \c columnCount() implementation does not need to look
391     for a particular item because all items are defined to have the same
392     number of columns associated with them.
393
394     \snippet itemviews/editabletreemodel/treemodel.cpp 2
395
396     As a result, the number of columns can be obtained directly from the root
397     item.
398
399     To enable items to be edited and selected, the \c flags() function needs
400     to be implemented so that it returns a combination of flags that includes
401     the Qt::ItemIsEditable and Qt::ItemIsSelectable flags as well as
402     Qt::ItemIsEnabled:
403
404     \snippet itemviews/editabletreemodel/treemodel.cpp 3
405
406     \target TreeModel::index
407     The model needs to be able to generate model indexes to allow other
408     components to request data and information about its structure. This task
409     is performed by the \c index() function, which is used to obtain model
410     indexes corresponding to children of a given parent item:
411
412     \snippet itemviews/editabletreemodel/treemodel.cpp 5
413
414     In this model, we only return model indexes for child items if the parent
415     index is invalid (corresponding to the root item) or if it has a zero
416     column number.
417
418     We use the custom \l{TreeModel::getItem}{getItem()} function to obtain
419     a \c TreeItem instance that corresponds to the model index supplied, and
420     request its child item that corresponds to the specified row.
421
422     \snippet itemviews/editabletreemodel/treemodel.cpp 6
423
424     Since each item contains information for an entire row of data, we create
425     a model index to uniquely identify it by calling
426     \l{QAbstractItemModel::}{createIndex()} it with the row and column numbers
427     and a pointer to the item. In the \l{TreeModel::data}{data()} function,
428     we will use the item pointer and column number to access the data
429     associated with the model index; in this model, the row number is not
430     needed to identify data.
431
432     \target TreeModel::parent
433     The \c parent() function supplies model indexes for parents of items
434     by finding the corresponding item for a given model index, using its
435     \l{TreeItem::parent}{parent()} function to obtain its parent item,
436     then creating a model index to represent the parent. (See
437     \l{Relating-items-using-model-indexes}{the above diagram}).
438
439     \snippet itemviews/editabletreemodel/treemodel.cpp 7
440
441     Items without parents, including the root item, are handled by returning
442     a null model index. Otherwise, a model index is created and returned as
443     in the \l{TreeModel::index}{index()} function, with a suitable row number,
444     but with a zero column number to be consistent with the scheme used in
445     the \l{TreeModel::index}{index()} implementation.
446
447     \target TreeModel::data
448     \target TreeModel::setupModelData
449
450 */