source: trunk/doc/src/frameworks-technologies/model-view-programming.qdoc

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

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

  • Property svn:eol-style set to native
File size: 111.0 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 \group model-view
30 \title Model/View Classes
31*/
32
33/*!
34 \page model-view-programming.html
35 \ingroup qt-basic-concepts
36
37 \title Model/View Programming
38 \brief A guide to Qt's extensible model/view architecture.
39
40 \section1 Introduction to Model/View Programming
41
42 Qt 4 introduced a new set of item view classes that use a model/view
43 architecture to manage the relationship between data and the way it
44 is presented to the user. The separation of functionality introduced by
45 this architecture gives developers greater flexibility to customize the
46 presentation of items, and provides a standard model interface to allow
47 a wide range of data sources to be used with existing item views.
48 In this document, we give a brief introduction to the model/view paradigm,
49 outline the concepts involved, and describe the architecture of the item
50 view system. Each of the components in the architecture is explained,
51 and examples are given that show how to use the classes provided.
52
53 \section2 The model/view architecture
54
55 Model-View-Controller (MVC) is a design pattern originating from
56 Smalltalk that is often used when building user interfaces.
57 In \l{Design Patterns}, Gamma et al. write:
58
59 \quotation
60 MVC consists of three kinds of objects. The Model is the application
61 object, the View is its screen presentation, and the Controller defines
62 the way the user interface reacts to user input. Before MVC, user
63 interface designs tended to lump these objects together. MVC decouples
64 them to increase flexibility and reuse.
65 \endquotation
66
67 If the view and the controller objects are combined, the result is
68 the model/view architecture. This still separates the way that data
69 is stored from the way that it is presented to the user, but provides
70 a simpler framework based on the same principles. This separation
71 makes it possible to display the same data in several different views,
72 and to implement new types of views, without changing the underlying
73 data structures.
74 To allow flexible handling of user input, we introduce the concept of
75 the \e delegate. The advantage of having a delegate in this framework
76 is that it allows the way items of data are rendered and edited to be
77 customized.
78
79 \table
80 \row \i \inlineimage modelview-overview.png
81 \i \bold{The model/view architecture}
82
83 The model communicates with a source of data, providing an \e interface
84 for the other components in the architecture. The nature of the
85 communication depends on the type of data source, and the way the model
86 is implemented.
87
88 The view obtains \e{model indexes} from the model; these are references
89 to items of data. By supplying model indexes to the model, the view can
90 retrieve items of data from the data source.
91
92 In standard views, a \e delegate renders the items of data. When an item
93 is edited, the delegate communicates with the model directly using
94 model indexes.
95 \endtable
96
97 Generally, the model/view classes can be separated into the three groups
98 described above: models, views, and delegates. Each of these components
99 is defined by \e abstract classes that provide common interfaces and,
100 in some cases, default implementations of features.
101 Abstract classes are meant to be subclassed in order to provide the full
102 set of functionality expected by other components; this also allows
103 specialized components to be written.
104
105 Models, views, and delegates communicate with each other using \e{signals
106 and slots}:
107
108 \list
109 \o Signals from the model inform the view about changes to the data
110 held by the data source.
111 \o Signals from the view provide information about the user's interaction
112 with the items being displayed.
113 \o Signals from the delegate are used during editing to tell the
114 model and view about the state of the editor.
115 \endlist
116
117 \section3 Models
118
119 All item models are based on the QAbstractItemModel class. This class
120 defines an interface that is used by views and delegates to access data.
121 The data itself does not have to be stored in the model; it can be held
122 in a data structure or repository provided by a separate class, a file,
123 a database, or some other application component.
124
125 The basic concepts surrounding models are presented in the section
126 on \l{Model Classes}.
127
128 QAbstractItemModel
129 provides an interface to data that is flexible enough to handle views
130 that represent data in the form of tables, lists, and trees. However,
131 when implementing new models for list and table-like data structures,
132 the QAbstractListModel and QAbstractTableModel classes are better
133 starting points because they provide appropriate default implementations
134 of common functions. Each of these classes can be subclassed to provide
135 models that support specialized kinds of lists and tables.
136
137 The process of subclassing models is discussed in the section on
138 \l{Creating New Models}.
139
140 Qt provides some ready-made models that can be used to handle items of
141 data:
142
143 \list
144 \o QStringListModel is used to store a simple list of QString items.
145 \o QStandardItemModel manages more complex tree structures of items, each
146 of which can contain arbitrary data.
147 \o QFileSystemModel provides information about files and directories in the
148 local filing system.
149 \o QSqlQueryModel, QSqlTableModel, and QSqlRelationalTableModel are used
150 to access databases using model/view conventions.
151 \endlist
152
153 If these standard models do not meet your requirements, you can subclass
154 QAbstractItemModel, QAbstractListModel, or QAbstractTableModel to create
155 your own custom models.
156
157 \section3 Views
158
159 Complete implementations are provided for different kinds of
160 views: QListView displays a list of items, QTableView displays data
161 from a model in a table, and QTreeView shows model items of data in a
162 hierarchical list. Each of these classes is based on the
163 QAbstractItemView abstract base class. Although these classes are
164 ready-to-use implementations, they can also be subclassed to provide
165 customized views.
166
167 The available views are examined in the section on \l{View Classes}.
168
169 \section3 Delegates
170
171 QAbstractItemDelegate is the abstract base class for delegates in the
172 model/view framework. Since Qt 4.4, the default delegate implementation is
173 provided by QStyledItemDelegate, and this is used as the default delegate
174 by Qt's standard views. However, QStyledItemDelegate and QItemDelegate are
175 independent alternatives to painting and providing editors for items in
176 views. The difference between them is that QStyledItemDelegate uses the
177 current style to paint its items. We therefore recommend using
178 QStyledItemDelegate as the base class when implementing custom delegates or
179 when working with Qt style sheets.
180
181 Delegates are described in the section on \l{Delegate Classes}.
182
183 \section3 Sorting
184
185 There are two ways of approaching sorting in the model/view
186 architecture; which approach to choose depends on your underlying
187 model.
188
189 If your model is sortable, i.e, if it reimplements the
190 QAbstractItemModel::sort() function, both QTableView and QTreeView
191 provide an API that allows you to sort your model data
192 programmatically. In addition, you can enable interactive sorting
193 (i.e. allowing the users to sort the data by clicking the view's
194 headers), by connecting the QHeaderView::sortIndicatorChanged() signal
195 to the QTableView::sortByColumn() slot or the
196 QTreeView::sortByColumn() slot, respectively.
197
198 The alternative approach, if your model do not have the required
199 interface or if you want to use a list view to present your data,
200 is to use a proxy model to transform the structure of your model
201 before presenting the data in the view. This is covered in detail
202 in the section on \l {Proxy Models}.
203
204 \section3 Convenience classes
205
206 A number of \e convenience classes are derived from the standard view
207 classes for the benefit of applications that rely on Qt's item-based
208 item view and table classes. They are not intended to be subclassed,
209 but simply exist to provide a familiar interface to the equivalent classes
210 in Qt 3.
211 Examples of such classes include \l QListWidget, \l QTreeWidget, and
212 \l QTableWidget; these provide similar behavior to the \c QListBox,
213 \c QListView, and \c QTable classes in Qt 3.
214
215 These classes are less flexible than the view classes, and cannot be
216 used with arbitrary models. We recommend that you use a model/view
217 approach to handling data in item views unless you strongly need an
218 item-based set of classes.
219
220 If you wish to take advantage of the features provided by the model/view
221 approach while still using an item-based interface, consider using view
222 classes, such as QListView, QTableView, and QTreeView with
223 QStandardItemModel.
224
225 \section1 Using models and views
226
227 The following sections explain how to use the model/view pattern
228 in Qt. Each section includes an an example and is followed by a
229 section showing how to create new components.
230
231 \section2 Two models included in Qt
232
233 Two of the standard models provided by Qt are QStandardItemModel and
234 QFileSystemModel. QStandardItemModel is a multi-purpose model that can be
235 used to represent various different data structures needed by list, table,
236 and tree views. This model also holds the items of data.
237 QFileSystemModel is a model that maintains information about the contents
238 of a directory. As a result, it does not hold any items of data itself, but
239 simply represents files and directories on the local filing system.
240
241 QFileSystemModel provides a ready-to-use model to experiment with, and can be
242 easily configured to use existing data. Using this model, we can show how
243 to set up a model for use with ready-made views, and explore how to
244 manipulate data using model indexes.
245
246 \section2 Using views with an existing model
247
248 The QListView and QTreeView classes are the most suitable views
249 to use with QFileSystemModel. The example presented below displays the
250 contents of a directory in a tree view next to the same information in
251 a list view. The views share the user's selection so that the selected
252 items are highlighted in both views.
253
254 \img shareddirmodel.png
255
256 We set up a QFileSystemModel so that it is ready for use, and create some
257 views to display the contents of a directory. This shows the simplest
258 way to use a model. The construction and use of the model is
259 performed from within a single \c main() function:
260
261 \snippet doc/src/snippets/shareddirmodel/main.cpp 0
262
263 The model is set up to use data from a certain file system. The call to
264 \l{QFileSystemModel::}{setRootPath()} tell the model which drive on the
265 file system to expose to the views.
266
267 We create two views so that we can examine the items held in the model in two
268 different ways:
269
270 \snippet doc/src/snippets/shareddirmodel/main.cpp 5
271
272 The views are constructed in the same way as other widgets. Setting up
273 a view to display the items in the model is simply a matter of calling its
274 \l{QAbstractItemView::setModel()}{setModel()} function with the directory
275 model as the argument. We filter the data supplied by the model by calling
276 the \l{QAbstractItemView::}{setRootIndex()} function on each view, passing
277 a suitable \e{model index} from the file system model for the current
278 directory.
279
280 The \c index() function used in this case is unique to QFileSystemModel; we
281 supply it with a directory and it returns a model index. Model indexes are
282 discussed in \l{Model Classes}.
283
284 The rest of the function just displays the views within a splitter
285 widget, and runs the application's event loop:
286
287 \snippet doc/src/snippets/shareddirmodel/main.cpp 8
288
289 In the above example, we neglected to mention how to handle selections
290 of items. This subject is covered in more detail in the section about
291 \l{Handling Selections in Item Views}.
292
293 \section1 Model classes
294
295 Before examining how selections are handled, you may find it
296 useful to examine the concepts used in the model/view framework.
297
298 \section2 Basic concepts
299
300 In the model/view architecture, the model provides a standard interface
301 that views and delegates use to access data. In Qt, the standard
302 interface is defined by the QAbstractItemModel class. No matter how the
303 items of data are stored in any underlying data structure, all subclasses
304 of QAbstractItemModel represent the data as a hierarchical structure
305 containing tables of items. Views use this \e convention to access items
306 of data in the model, but they are not restricted in the way that they
307 present this information to the user.
308
309 \image modelview-models.png
310
311 Models also notify any attached views about changes to data through the
312 signals and slots mechanism.
313
314 This section describes some basic concepts that are central to the way
315 item of data are accessed by other components via a model class. More
316 advanced concepts are discussed in later sections.
317
318 \section3 Model indexes
319
320 To ensure that the representation of the data is kept separate from the
321 way it is accessed, the concept of a \e{model index} is introduced. Each
322 piece of information that can be obtained via a model is represented by
323 a model index. Views and delegates use these indexes to request items of
324 data to display.
325
326 As a result, only the model needs to know how to obtain data, and the type
327 of data managed by the model can be defined fairly generally. Model indexes
328 contain a pointer to the model that created them, and this prevents
329 confusion when working with more than one model.
330
331 \snippet doc/src/snippets/code/doc_src_model-view-programming.qdoc 0
332
333 Model indexes provide \e temporary references to pieces of information, and
334 can be used to retrieve or modify data via the model. Since models may
335 reorganize their internal structures from time to time, model indexes may
336 become invalid, and \e{should not be stored}. If a long-term reference to a
337 piece of information is required, a \e{persistent model index} must be
338 created. This provides a reference to the information that the model keeps
339 up-to-date. Temporary model indexes are provided by the QModelIndex class,
340 and persistent model indexes are provided by the QPersistentModelIndex
341 class.
342
343 To obtain a model index that corresponds to an item of data, three
344 properties must be specified to the model: a row number, a column number,
345 and the model index of a parent item. The following sections describe
346 and explain these properties in detail.
347
348 \section3 Rows and columns
349
350 In its most basic form, a model can be accessed as a simple table in which
351 items are located by their row and column numbers. \e{This does not mean
352 that the underlying pieces of data are stored in an array structure}; the
353 use of row and column numbers is only a convention to allow components to
354 communicate with each other. We can retrieve information about any given
355 item by specifying its row and column numbers to the model, and we receive
356 an index that represents the item:
357
358 \snippet doc/src/snippets/code/doc_src_model-view-programming.qdoc 1
359
360 Models that provide interfaces to simple, single level data structures like
361 lists and tables do not need any other information to be provided but, as
362 the above code indicates, we need to supply more information when obtaining
363 a model index.
364
365 \table
366 \row \i \inlineimage modelview-tablemodel.png
367 \i \bold{Rows and columns}
368
369 The diagram shows a representation of a basic table model in which each
370 item is located by a pair of row and column numbers. We obtain a model
371 index that refers to an item of data by passing the relevant row and
372 column numbers to the model.
373
374 \snippet doc/src/snippets/code/doc_src_model-view-programming.qdoc 2
375
376 Top level items in a model are always referenced by specifying
377 \c QModelIndex() as their parent item. This is discussed in the next
378 section.
379 \endtable
380
381 \section3 Parents of items
382
383 The table-like interface to item data provided by models is ideal when
384 using data in a table or list view; the row and column number system maps
385 exactly to the way the views display items. However, structures such as
386 tree views require the model to expose a more flexible interface to the
387 items within. As a result, each item can also be the parent of another
388 table of items, in much the same way that a top-level item in a tree view
389 can contain another list of items.
390
391 When requesting an index for a model item, we must provide some information
392 about the item's parent. Outside the model, the only way to refer to an
393 item is through a model index, so a parent model index must also be given:
394
395 \snippet doc/src/snippets/code/doc_src_model-view-programming.qdoc 3
396
397 \table
398 \row \i \inlineimage modelview-treemodel.png
399 \i \bold{Parents, rows, and columns}
400
401 The diagram shows a representation of a tree model in which each item is
402 referred to by a parent, a row number, and a column number.
403
404 Items "A" and "C" are represented as top-level siblings in the model:
405
406 \snippet doc/src/snippets/code/doc_src_model-view-programming.qdoc 4
407
408 Item "A" has a number of children. A model index for item "B" is
409 obtained with the following code:
410
411 \snippet doc/src/snippets/code/doc_src_model-view-programming.qdoc 5
412 \endtable
413
414 \section3 Item roles
415
416 Items in a model can perform various \e roles for other components,
417 allowing different kinds of data to be supplied for different situations.
418 For example, Qt::DisplayRole is used to access a string that can be
419 displayed as text in a view. Typically, items contain data for a number of
420 different roles, and the standard roles are defined by Qt::ItemDataRole.
421
422 We can ask the model for the item's data by passing it the model index
423 corresponding to the item, and by specifying a role to obtain the type
424 of data we want:
425
426 \snippet doc/src/snippets/code/doc_src_model-view-programming.qdoc 6
427
428 \table
429 \row \i \inlineimage modelview-roles.png
430 \i \bold{Item roles}
431
432 The role indicates to the model which type of data is being referred to.
433 Views can display the roles in different ways, so it is important to
434 supply appropriate information for each role.
435
436 The \l{Creating New Models} section covers some specific uses of roles in
437 more detail.
438 \endtable
439
440 Most common uses for item data are covered by the standard roles defined in
441 Qt::ItemDataRole. By supplying appropriate item data for each role, models
442 can provide hints to views and delegates about how items should be
443 presented to the user. Different kinds of views have the freedom to
444 interpret or ignore this information as required. It is also possible to
445 define additional roles for application-specific purposes.
446
447 \section3 Summary
448
449 \list
450 \o Model indexes give views and delegates information about the location
451 of items provided by models in a way that is independent of any
452 underlying data structures.
453 \o Items are referred to by their row and column numbers, and by the model
454 index of their parent items.
455 \o Model indexes are constructed by models at the request of other
456 components, such as views and delegates.
457 \o If a valid model index is specified for the parent item when an index is
458 requested using \l{QAbstractItemModel::index()}{index()}, the index
459 returned refers to an item beneath that parent item in the model.
460 The index obtained refers to a child of that item.
461 \o If an invalid model index is specified for the parent item when an index
462 is requested using \l{QAbstractItemModel::index()}{index()}, the index
463 returned refers to a top-level item in the model.
464 \o The \l{Qt::ItemDataRole}{role} distinguishes between the
465 different kinds of data associated with an item.
466 \endlist
467
468 \section2 Using model indexes
469
470 To demonstrate how data can be retrieved from a model, using model
471 indexes, we set up a QFileSystemModel without a view and display the
472 names of files and directories in a widget.
473 Although this does not show a normal way of using a model, it demonstrates
474 the conventions used by models when dealing with model indexes.
475
476 We construct a file system model in the following way:
477
478 \snippet doc/src/snippets/simplemodel-use/main.cpp 0
479
480 In this case, we set up a default QFileSystemModel, obtain a parent index
481 using a specific implementation of \l{QFileSystemModel::}{index()}
482 provided by that model, and we count the number of rows in the model using
483 the \l{QFileSystemModel::}{rowCount()} function.
484
485 For simplicity, we are only interested in the items in the first column
486 of the model. We examine each row in turn, obtaining a model index for
487 the first item in each row, and read the data stored for that item
488 in the model.
489
490 \snippet doc/src/snippets/simplemodel-use/main.cpp 1
491
492 To obtain a model index, we specify the row number, column number (zero
493 for the first column), and the appropriate model index for the parent
494 of all the items that we want.
495 The text stored in each item is retrieved using the model's
496 \l{QFileSystemModel::}{data()} function. We specify the model index and
497 the \l{Qt::ItemDataRole}{DisplayRole} to obtain data for the
498 item in the form of a string.
499
500 \snippet doc/src/snippets/simplemodel-use/main.cpp 2
501 \codeline
502 \snippet doc/src/snippets/simplemodel-use/main.cpp 3
503
504 The above example demonstrates the basic principles used to retrieve
505 data from a model:
506
507 \list
508 \i The dimensions of a model can be found using
509 \l{QAbstractItemModel::rowCount()}{rowCount()} and
510 \l{QAbstractItemModel::columnCount()}{columnCount()}.
511 These functions generally require a parent model index to be
512 specified.
513 \i Model indexes are used to access items in the model. The row, column,
514 and parent model index are needed to specify the item.
515 \i To access top-level items in a model, specify a null model index
516 as the parent index with \c QModelIndex().
517 \i Items contain data for different roles. To obtain the data for a
518 particular role, both the model index and the role must be supplied
519 to the model.
520 \endlist
521
522 \section2 Further reading
523
524 New models can be created by implementing the standard interface
525 provided by QAbstractItemModel. In the \l{Creating New Models}
526 section, we demonstrate this by creating a convenient ready-to-use
527 model for holding lists of strings.
528
529 \section1 View classes
530
531 \section2 Concepts
532
533 In the model/view architecture, the view obtains items of data from the
534 model and presents them to the user. The way that the data is
535 presented need not resemble the representation of the data provided by
536 the model, and may be \e{completely different} from the underlying data
537 structure used to store items of data.
538
539 The separation of content and presentation is achieved by the use of a
540 standard model interface provided by QAbstractItemModel, a standard view
541 interface provided by QAbstractItemView, and the use of model indexes
542 that represent items of data in a general way.
543 Views typically manage the overall layout of the data obtained from
544 models. They may render individual items of data themselves, or use
545 \l{Delegate Classes}{delegates} to handle both rendering and editing
546 features.
547
548 As well as presenting data, views handle navigation between items,
549 and some aspects of item selection. The views also implement basic
550 user interface features, such as context menus and drag and drop.
551 A view can provide default editing facilities for items, or it may
552 work with a \l{Delegate Classes}{delegate} to provide a custom
553 editor.
554
555 A view can be constructed without a model, but a model must be
556 provided before it can display useful information. Views keep track of
557 the items that the user has selected through the use of
558 \l{Handling Selections in Item Views}{selections} which can be maintained
559 separately for each view, or shared between multiple views.
560
561 Some views, such as QTableView and QTreeView, display headers as well
562 as items. These are also implemented by a view class, QHeaderView.
563 Headers usually access the same model as the view that contains them.
564 They retrieve data from the model using the
565 \l{QAbstractItemModel::headerData()} function, and usually display
566 header information in the form of a label. New headers can be
567 subclassed from the QHeaderView class to provide more specialized
568 labels for views.
569
570 \section2 Using an existing view
571
572 Qt provides three ready-to-use view classes that present data from
573 models in ways that are familiar to most users.
574 QListView can display items from a model as a simple list, or in the
575 form of a classic icon view. QTreeView displays items from a
576 model as a hierarchy of lists, allowing deeply nested structures to be
577 represented in a compact way. QTableView presents items from a model
578 in the form of a table, much like the layout of a spreadsheet
579 application.
580
581 \img standard-views.png
582
583 The default behavior of the standard views shown above should be
584 sufficient for most applications. They provide basic editing
585 facilities, and can be customized to suit the needs of more specialized
586 user interfaces.
587
588 \section3 Using a model
589
590 We take the string list model that \l{Creating New Models}{we created as
591 an example model}, set it up with some data, and construct a view to
592 display the contents of the model. This can all be performed within a
593 single function:
594
595 \snippet doc/src/snippets/stringlistmodel/main.cpp 0
596
597 Note that the \c StringListModel is declared as a \l QAbstractItemModel.
598 This allows us to use the abstract interface to the model, and
599 ensures that the code still works, even if we replace the string list
600 model with a different model.
601
602 The list view provided by \l QListView is sufficient for presenting
603 the items in the string list model. We construct the view, and set up
604 the model using the following lines of code:
605
606 \snippet doc/src/snippets/stringlistmodel/main.cpp 2
607 \snippet doc/src/snippets/stringlistmodel/main.cpp 4
608
609 The view is shown in the normal way:
610
611 \snippet doc/src/snippets/stringlistmodel/main.cpp 5
612
613 The view renders the contents of a model, accessing data via the model's
614 interface. When the user tries to edit an item, the view uses a default
615 delegate to provide an editor widget.
616
617 \img stringlistmodel.png
618
619 The above image shows how a QListView represents the data in the string
620 list model. Since the model is editable, the view automatically allows
621 each item in the list to be edited using the default delegate.
622
623 \section3 Using multiple views of a model
624
625 Providing multiple views onto the same model is simply a matter of
626 setting the same model for each view. In the following code we create
627 two table views, each using the same simple table model which we have
628 created for this example:
629
630 \snippet doc/src/snippets/sharedtablemodel/main.cpp 0
631 \codeline
632 \snippet doc/src/snippets/sharedtablemodel/main.cpp 1
633
634 The use of signals and slots in the model/view architecture means that
635 changes to the model can be propagated to all the attached views,
636 ensuring that we can always access the same data regardless of the
637 view being used.
638
639 \img sharedmodel-tableviews.png
640
641 The above image shows two different views onto the same model, each
642 containing a number of selected items. Although the data from the model
643 is shown consistently across view, each view maintains its own internal
644 selection model. This can be useful in certain situations but, for
645 many applications, a shared selection model is desirable.
646
647 \section2 Handling selections of items
648
649 The mechanism for handling selections of items within views is provided
650 by the \l QItemSelectionModel class. All of the standard views construct
651 their own selection models by default, and interact with them in the
652 normal way. The selection model being used by a view can be obtained
653 through the \l{QAbstractItemView::selectionModel()}{selectionModel()}
654 function, and a replacement selection model can be specified with
655 \l{QAbstractItemView::setSelectionModel()}{setSelectionModel()}.
656 The ability to control the selection model used by a view is useful
657 when we want to provide multiple consistent views onto the same model
658 data.
659
660 Generally, unless you are subclassing a model or view, you don't
661 need to manipulate the contents of selections directly. However,
662 the interface to the selection model can be accessed, if required,
663 and this is explored in \l{Handling Selections in Item Views}.
664
665 \section3 Sharing selections among views
666
667 Although it is convenient that the view classes provide their own
668 selection models by default, when we use more than one view onto the
669 same model it is often desirable that both the model's data and the
670 user's selection are shown consistently in all views.
671 Since the view classes allow their internal selection models to be
672 replaced, we can achieve a unified selection between views with the
673 following line:
674
675 \snippet doc/src/snippets/sharedtablemodel/main.cpp 2
676
677 The second view is given the selection model for the first view.
678 Both views now operate on the same selection model, keeping both
679 the data and the selected items synchronized.
680
681 \img sharedselection-tableviews.png
682
683 In the example shown above, two views of the same type were used to
684 display the same model's data. However, if two different types of view
685 were used, the selected items may be represented very differently in
686 each view; for example, a contiguous selection in a table view can be
687 represented as a fragmented set of highlighted items in a tree view.
688
689 \section1 Delegate classes
690
691 \section2 Concepts
692
693 Unlike the Model-View-Controller pattern, the model/view design does not
694 include a completely separate component for managing interaction with
695 the user. Generally, the view is responsible for the presentation of
696 model data to the user, and for processing user input. To allow some
697 flexibility in the way this input is obtained, the interaction is
698 performed by delegates. These components provide input capabilities
699 and are also responsible for rendering individual items in some views.
700 The standard interface for controlling delegates is defined in the
701 \l QAbstractItemDelegate class.
702
703 Delegates are expected to be able to render their contents themselves
704 by implementing the \l{QItemDelegate::paint()}{paint()}
705 and \l{QItemDelegate::sizeHint()}{sizeHint()} functions.
706 However, simple widget-based delegates can subclass \l QItemDelegate
707 instead of \l QAbstractItemDelegate, and take advantage of the default
708 implementations of these functions.
709
710 Editors for delegates can be implemented either by using widgets to manage
711 the editing process or by handling events directly.
712 The first approach is covered later in this section, and it is also
713 shown in the \l{Spin Box Delegate Example}{Spin Box Delegate} example.
714
715 The \l{Pixelator Example}{Pixelator} example shows how to create a
716 custom delegate that performs specialized rendering for a table view.
717
718 \section2 Using an existing delegate
719
720 The standard views provided with Qt use instances of \l QItemDelegate
721 to provide editing facilities. This default implementation of the
722 delegate interface renders items in the usual style for each of the
723 standard views: \l QListView, \l QTableView, and \l QTreeView.
724
725 All the standard roles are handled by the default delegate used by
726 the standard views. The way these are interpreted is described in the
727 QItemDelegate documentation.
728
729 The delegate used by a view is returned by the
730 \l{QAbstractItemView::itemDelegate()}{itemDelegate()} function.
731 The \l{QAbstractItemView::setItemDelegate()}{setItemDelegate()} function
732 allows you to install a custom delegate for a standard view, and it is
733 necessary to use this function when setting the delegate for a custom
734 view.
735
736 \section2 A simple delegate
737
738 The delegate implemented here uses a \l QSpinBox to provide
739 editing facilities, and is mainly intended for use with models
740 that display integers. Although we set up a custom integer-based
741 table model for this purpose, we could easily have used \l
742 QStandardItemModel instead, since the custom delegate controls
743 data entry. We construct a table view to display the contents of
744 the model, and this will use the custom delegate for editing.
745
746 \img spinboxdelegate-example.png
747
748 We subclass the delegate from \l QItemDelegate because we do not want
749 to write custom display functions. However, we must still provide
750 functions to manage the editor widget:
751
752 \snippet examples/itemviews/spinboxdelegate/delegate.h 0
753
754 Note that no editor widgets are set up when the delegate is
755 constructed. We only construct an editor widget when it is needed.
756
757 \section3 Providing an editor
758
759 In this example, when the table view needs to provide an editor, it
760 asks the delegate to provide an editor widget that is appropriate
761 for the item being modified. The
762 \l{QAbstractItemDelegate::createEditor()}{createEditor()} function is
763 supplied with everything that the delegate needs to be able to set up
764 a suitable widget:
765
766 \snippet examples/itemviews/spinboxdelegate/delegate.cpp 1
767
768 Note that we do not need to keep a pointer to the editor widget because
769 the view takes responsibility for destroying it when it is no longer
770 needed.
771
772 We install the delegate's default event filter on the editor to ensure
773 that it provides the standard editing shortcuts that users expect.
774 Additional shortcuts can be added to the editor to allow more
775 sophisticated behavior; these are discussed in the section on
776 \l{#EditingHints}{Editing Hints}.
777
778 The view ensures that the editor's data and geometry are set
779 correctly by calling functions that we define later for these purposes.
780 We can create different editors depending on the model index supplied
781 by the view. For example, if we have a column of integers and a column
782 of strings we could return either a \c QSpinBox or a \c QLineEdit,
783 depending on which column is being edited.
784
785 The delegate must provide a function to copy model data into the
786 editor. In this example, we read the data stored in the
787 \l{Qt::ItemDataRole}{display role}, and set the value in the
788 spin box accordingly.
789
790 \snippet examples/itemviews/spinboxdelegate/delegate.cpp 2
791
792 In this example, we know that the editor widget is a spin box, but we
793 could have provided different editors for different types of data in
794 the model, in which case we would need to cast the widget to the
795 appropriate type before accessing its member functions.
796
797 \section3 Submitting data to the model
798
799 When the user has finished editing the value in the spin box, the view
800 asks the delegate to store the edited value in the model by calling the
801 \l{QAbstractItemDelegate::setModelData()}{setModelData()} function.
802
803 \snippet examples/itemviews/spinboxdelegate/delegate.cpp 3
804
805 Since the view manages the editor widgets for the delegate, we only
806 need to update the model with the contents of the editor supplied.
807 In this case, we ensure that the spin box is up-to-date, and update
808 the model with the value it contains using the index specified.
809
810 The standard \l QItemDelegate class informs the view when it has
811 finished editing by emitting the
812 \l{QAbstractItemDelegate::closeEditor()}{closeEditor()} signal.
813 The view ensures that the editor widget is closed and destroyed. In
814 this example, we only provide simple editing facilities, so we need
815 never emit this signal.
816
817 All the operations on data are performed through the interface
818 provided by \l QAbstractItemModel. This makes the delegate mostly
819 independent from the type of data it manipulates, but some
820 assumptions must be made in order to use certain types of
821 editor widgets. In this example, we have assumed that the model
822 always contains integer values, but we can still use this
823 delegate with different kinds of models because \l{QVariant}
824 provides sensible default values for unexpected data.
825
826 \section3 Updating the editor's geometry
827
828 It is the responsibility of the delegate to manage the editor's
829 geometry. The geometry must be set when the editor is created, and
830 when the item's size or position in the view is changed. Fortunately,
831 the view provides all the necessary geometry information inside a
832 \l{QStyleOptionViewItem}{view option} object.
833
834 \snippet examples/itemviews/spinboxdelegate/delegate.cpp 4
835
836 In this case, we just use the geometry information provided by the
837 view option in the item rectangle. A delegate that renders items with
838 several elements would not use the item rectangle directly. It would
839 position the editor in relation to the other elements in the item.
840
841 \target EditingHints
842 \section3 Editing hints
843
844 After editing, delegates should provide hints to the other components
845 about the result of the editing process, and provide hints that will
846 assist any subsequent editing operations. This is achieved by
847 emitting the \l{QAbstractItemDelegate::closeEditor()}{closeEditor()}
848 signal with a suitable hint. This is taken care of by the default
849 QItemDelegate event filter which we installed on the spin box when
850 it was constructed.
851
852 The behavior of the spin box could be adjusted to make it more user
853 friendly. In the default event filter supplied by QItemDelegate, if
854 the user hits \key Return to confirm their choice in the spin box,
855 the delegate commits the value to the model and closes the spin box.
856 We can change this behavior by installing our own event filter on the
857 spin box, and provide editing hints that suit our needs; for example,
858 we might emit \l{QAbstractItemDelegate::closeEditor()}{closeEditor()}
859 with the \l{QAbstractItemDelegate::EndEditHint}{EditNextItem} hint to
860 automatically start editing the next item in the view.
861
862 Another approach that does not require the use of an event
863 filter is to provide our own editor widget, perhaps subclassing
864 QSpinBox for convenience. This alternative approach would give us
865 more control over how the editor widget behaves at the cost of
866 writing additional code. It is usually easier to install an event
867 filter in the delegate if you need to customize the behavior of
868 a standard Qt editor widget.
869
870 Delegates do not have to emit these hints, but those that do not will
871 be less integrated into applications, and will be less usable than
872 those that emit hints to support common editing actions.
873
874 \section1 Handling selections in item views
875
876 \section2 Concepts
877
878 The selection model used in the item view classes offers many improvements
879 over the selection model used in Qt 3. It provides a more general
880 description of selections based on the facilities of the model/view
881 architecture. Although the standard classes for manipulating selections are
882 sufficient for the item views provided, the selection model allows you to
883 create specialized selection models to suit the requirements for your own
884 item models and views.
885
886 Information about the items selected in a view is stored in an instance of
887 the \l QItemSelectionModel class. This maintains model indexes for items in
888 a single model, and is independent of any views. Since there can be many
889 views onto a model, it is possible to share selections between views,
890 allowing applications to show multiple views in a consistent way.
891
892 Selections are made up of \e{selection ranges}. These efficiently maintain
893 information about large selections of items by recording only the starting
894 and ending model indexes for each range of selected items. Non-contiguous
895 selections of items are constructed by using more than one selection range
896 to describe the selection.
897
898 Selections are applied to a collection of model indexes held by a selection
899 model. The most recent selection of items applied is known as the
900 \e{current selection}. The effects of this selection can be modified even
901 after its application through the use of certain types of selection
902 commands. These are discussed later in this section.
903
904 \section3 Current item and selected items
905
906 In a view, there is always a current item and a selected item - two
907 independent states. An item can be the current item and selected at the
908 same time. The view is responsible for ensuring that there is always a
909 current item as keyboard navigation, for example, requires a current item.
910
911 The table below highlights the differences between current item and
912 selected items.
913
914 \table
915 \header
916 \o Current Item
917 \o Selected Items
918
919 \row
920 \o There can only be one current item.
921 \o There can be multiple selected items.
922 \row
923 \o The current item will be changed with key navigation or mouse
924 button clicks.
925 \o The selected state of items is set or unset, depending on several
926 pre-defined modes - e.g., single selection, multiple selection,
927 etc. - when the user interacts with the items.
928 \row
929 \o The current item will be edited if the edit key, \gui F2, is
930 pressed or the item is double-clicked (provided that editing is
931 enabled).
932 \o The current item can be used together with an anchor to specify a
933 range that should be selected or deselected (or a combination of
934 the two).
935 \row
936 \o The current item is indicated by the focus rectangle.
937 \o The selected items are indicated with the selection rectangle.
938 \endtable
939
940 When manipulating selections, it is often helpful to think of
941 \l QItemSelectionModel as a record of the selection state of all the items
942 in an item model. Once a selection model is set up, collections of items
943 can be selected, deselected, or their selection states can be toggled
944 without the need to know which items are already selected. The indexes of
945 all selected items can be retrieved at any time, and other components can
946 be informed of changes to the selection model via the signals and slots
947 mechanism.
948
949 \section2 Using a selection model
950
951 The standard view classes provide default selection models that can
952 be used in most applications. A selection model belonging to one view
953 can be obtained using the view's
954 \l{QAbstractItemView::selectionModel()}{selectionModel()} function,
955 and shared between many views with
956 \l{QAbstractItemView::setSelectionModel()}{setSelectionModel()},
957 so the construction of new selection models is generally not required.
958
959 A selection is created by specifying a model, and a pair of model
960 indexes to a \l QItemSelection. This uses the indexes to refer to items
961 in the given model, and interprets them as the top-left and bottom-right
962 items in a block of selected items.
963 To apply the selection to items in a model requires the selection to be
964 submitted to a selection model; this can be achieved in a number of ways,
965 each having a different effect on the selections already present in the
966 selection model.
967
968 \section3 Selecting items
969
970 To demonstrate some of the principal features of selections, we construct
971 an instance of a custom table model with 32 items in total, and open a
972 table view onto its data:
973
974 \snippet doc/src/snippets/itemselection/main.cpp 0
975
976 The table view's default selection model is retrieved for later use.
977 We do not modify any items in the model, but instead select a few
978 items that the view will display at the top-left of the table. To do
979 this, we need to retrieve the model indexes corresponding to the
980 top-left and bottom-right items in the region to be selected:
981
982 \snippet doc/src/snippets/itemselection/main.cpp 1
983
984 To select these items in the model, and see the corresponding change
985 in the table view, we need to construct a selection object then apply
986 it to the selection model:
987
988 \snippet doc/src/snippets/itemselection/main.cpp 2
989
990 The selection is applied to the selection model using a command
991 defined by a combination of
992 \l{QItemSelectionModel::SelectionFlag}{selection flags}.
993 In this case, the flags used cause the items recorded in the
994 selection object to be included in the selection model, regardless
995 of their previous state. The resulting selection is shown by the view.
996
997 \img selected-items1.png
998
999 The selection of items can be modified using various operations that
1000 are defined by the selection flags. The selection that results from
1001 these operations may have a complex structure, but it is represented
1002 efficiently by the selection model. The use of different selection
1003 flags to manipulate the selected items is described when we examine
1004 how to update a selection.
1005
1006 \section3 Reading the selection state
1007
1008 The model indexes stored in the selection model can be read using
1009 the \l{QItemSelectionModel::selectedIndexes()}{selectedIndexes()}
1010 function. This returns an unsorted list of model indexes that we can
1011 iterate over as long as we know which model they are for:
1012
1013 \snippet doc/src/snippets/reading-selections/window.cpp 0
1014
1015 The above code uses Qt's convenient \l{Container Classes}{foreach
1016 keyword} to iterate over, and modify, the items corresponding to the
1017 indexes returned by the selection model.
1018
1019 The selection model emits signals to indicate changes in the
1020 selection. These notify other components about changes to both the
1021 selection as a whole and the currently focused item in the item
1022 model. We can connect the
1023 \l{QItemSelectionModel::selectionChanged()}{selectionChanged()}
1024 signal to a slot, and examine the items in the model that are selected or
1025 deselected when the selection changes. The slot is called with two
1026 \l{QItemSelection} objects: one contains a list of indexes that
1027 correspond to newly selected items; the other contains indexes that
1028 correspond to newly deselected items.
1029
1030 In the following code, we provide a slot that receives the
1031 \l{QItemSelectionModel::selectionChanged()}{selectionChanged()}
1032 signal, fills in the selected items with
1033 a string, and clears the contents of the deselected items.
1034
1035 \snippet doc/src/snippets/updating-selections/window.cpp 0
1036 \snippet doc/src/snippets/updating-selections/window.cpp 1
1037 \codeline
1038 \snippet doc/src/snippets/updating-selections/window.cpp 2
1039
1040 We can keep track of the currently focused item by connecting the
1041 \l{QItemSelectionModel::currentChanged()}{currentChanged()} signal
1042 to a slot that is called with two model indexes. These correspond to
1043 the previously focused item, and the currently focused item.
1044
1045 In the following code, we provide a slot that receives the
1046 \l{QItemSelectionModel::currentChanged()}{currentChanged()} signal,
1047 and uses the information provided to update the status bar of a
1048 \l QMainWindow:
1049
1050 \snippet doc/src/snippets/updating-selections/window.cpp 3
1051
1052 Monitoring selections made by the user is straightforward with these
1053 signals, but we can also update the selection model directly.
1054
1055 \section3 Updating a selection
1056
1057 Selection commands are provided by a combination of selection flags,
1058 defined by \l{QItemSelectionModel::SelectionFlag}.
1059 Each selection flag tells the selection model how to update its
1060 internal record of selected items when either of the
1061 \l{QItemSelection::select()}{select()} functions are called.
1062 The most commonly used flag is the
1063 \l{QItemSelectionModel::SelectionFlag}{Select} flag
1064 which instructs the selection model to record the specified items as
1065 being selected. The
1066 \l{QItemSelectionModel::SelectionFlag}{Toggle} flag causes the
1067 selection model to invert the state of the specified items,
1068 selecting any deselected items given, and deselecting any currently
1069 selected items. The \l{QItemSelectionModel::SelectionFlag}{Deselect}
1070 flag deselects all the specified items.
1071
1072 Individual items in the selection model are updated by creating a
1073 selection of items, and applying them to the selection model. In the
1074 following code, we apply a second selection of items to the table
1075 model shown above, using the
1076 \l{QItemSelectionModel::SelectionFlag}{Toggle} command to invert the
1077 selection state of the items given.
1078
1079 \snippet doc/src/snippets/itemselection/main.cpp 3
1080
1081 The results of this operation are displayed in the table view,
1082 providing a convenient way of visualizing what we have achieved:
1083
1084 \img selected-items2.png
1085
1086 By default, the selection commands only operate on the individual
1087 items specified by the model indexes. However, the flag used to
1088 describe the selection command can be combined with additional flags
1089 to change entire rows and columns. For example if you call
1090 \l{QItemSelectionModel::select()}{select()} with only one index, but
1091 with a command that is a combination of
1092 \l{QItemSelectionModel::SelectionFlag}{Select} and
1093 \l{QItemSelectionModel::SelectionFlag}{Rows}, the
1094 entire row containing the item referred to is selected.
1095 The following code demonstrates the use of the
1096 \l{QItemSelectionModel::SelectionFlag}{Rows} and
1097 \l{QItemSelectionModel::SelectionFlag}{Columns} flags:
1098
1099 \snippet doc/src/snippets/itemselection/main.cpp 4
1100
1101 Although only four indexes are supplied to the selection model, the
1102 use of the
1103 \l{QItemSelectionModel::SelectionFlag}{Columns} and
1104 \l{QItemSelectionModel::SelectionFlag}{Rows} selection flags means
1105 that two columns and two rows are selected. The following image shows
1106 the result of these two selections:
1107
1108 \img selected-items3.png
1109
1110 The commands performed on the example model have all involved
1111 accumulating a selection of items in the model. It is also possible
1112 to clear the selection, or to replace the current selection with
1113 a new one.
1114
1115 To replace the current selection with a new selection, combine
1116 the other selection flags with the
1117 \l{QItemSelectionModel::SelectionFlag}{Current} flag. A command using
1118 this flag instructs the selection model to replace its current collection
1119 of model indexes with those specified in a call to
1120 \l{QItemSelectionModel::select()}{select()}.
1121 To clear all selections before you start adding new ones,
1122 combine the other selection flags with the
1123 \l{QItemSelectionModel::SelectionFlag}{Clear} flag. This
1124 has the effect of resetting the selection model's collection of model
1125 indexes.
1126
1127 \section3 Selecting all items in a model
1128
1129 To select all items in a model, it is necessary to create a
1130 selection for each level of the model that covers all items in that
1131 level. We do this by retrieving the indexes corresponding to the
1132 top-left and bottom-right items with a given parent index:
1133
1134 \snippet doc/src/snippets/reading-selections/window.cpp 2
1135
1136 A selection is constructed with these indexes and the model. The
1137 corresponding items are then selected in the selection model:
1138
1139 \snippet doc/src/snippets/reading-selections/window.cpp 3
1140
1141 This needs to be performed for all levels in the model.
1142 For top-level items, we would define the parent index in the usual way:
1143
1144 \snippet doc/src/snippets/reading-selections/window.cpp 1
1145
1146 For hierarchical models, the
1147 \l{QAbstractItemModel::hasChildren()}{hasChildren()} function is used to
1148 determine whether any given item is the parent of another level of
1149 items.
1150
1151 \section1 Creating new models
1152
1153 The separation of functionality between the model/view components allows
1154 models to be created that can take advantage of existing views. This
1155 approach lets us present data from a variety of sources using standard
1156 graphical user interface components, such as QListView, QTableView, and
1157 QTreeView.
1158
1159 The QAbstractItemModel class provides an interface that is flexible
1160 enough to support data sources that arrange information in hierarchical
1161 structures, allowing for the possibility that data will be inserted,
1162 removed, modified, or sorted in some way. It also provides support for
1163 drag and drop operations.
1164
1165 The QAbstractListModel and QAbstractTableModel classes provide support
1166 for interfaces to simpler non-hierarchical data structures, and are
1167 easier to use as a starting point for simple list and table models.
1168
1169 In this section, we create a simple read-only model to explore
1170 the basic principles of the model/view architecture. Later in this
1171 section, we adapt this simple model so that items can be modified
1172 by the user.
1173
1174 For an example of a more complex model, see the
1175 \l{itemviews/simpletreemodel}{Simple Tree Model} example.
1176
1177 The requirements of QAbstractItemModel subclasses is described in more
1178 detail in the \l{Model Subclassing Reference} document.
1179
1180 \section2 Designing a model
1181
1182 When creating a new model for an existing data structure, it is
1183 important to consider which type of model should be used to
1184 provide an interface onto the data. If the data structure can be
1185 represented as a list or table of items, you can subclass
1186 QAbstractListModel or QAbstractTableModel since these classes
1187 provide suitable default implementations for many functions.
1188
1189 However, if the underlying data structure can only be represented
1190 by a hierarchical tree structure, it is necessary to subclass
1191 QAbstractItemModel. This approach is taken in the
1192 \l{itemviews/simpletreemodel}{Simple Tree Model} example.
1193
1194 In this section, we implement a simple model based on a list of
1195 strings, so the QAbstractListModel provides an ideal base class on
1196 which to build.
1197
1198 Whatever form the underlying data structure takes, it is
1199 usually a good idea to supplement the standard QAbstractItemModel API
1200 in specialized models with one that allows more natural access to the
1201 underlying data structure. This makes it easier to populate the model
1202 with data, yet still enables other general model/view components to
1203 interact with it using the standard API. The model described below
1204 provides a custom constructor for just this purpose.
1205
1206 \section2 A read-only example model
1207
1208 The model implemented here is a simple, non-hierarchical, read-only data
1209 model based on the standard QStringListModel class. It has a \l QStringList
1210 as its internal data source, and implements only what is needed to make a
1211 functioning model. To make the implementation easier, we subclass
1212 \l QAbstractListModel because it defines sensible default behavior for list
1213 models, and it exposes a simpler interface than the \l QAbstractItemModel
1214 class.
1215
1216 When implementing a model it is important to remember that
1217 \l QAbstractItemModel does not store any data itself, it merely
1218 presents an interface that the views use to access the data.
1219 For a minimal read-only model it is only necessary to implement a few
1220 functions as there are default implementations for most of the
1221 interface. The class declaration is as follows:
1222
1223 \snippet doc/src/snippets/stringlistmodel/model.h 0
1224 \snippet doc/src/snippets/stringlistmodel/model.h 1
1225 \codeline
1226 \snippet doc/src/snippets/stringlistmodel/model.h 5
1227
1228 Apart from the model's constructor, we only need to implement two
1229 functions: \l{QAbstractItemModel::rowCount()}{rowCount()} returns the
1230 number of rows in the model and \l{QAbstractItemModel::data()}{data()}
1231 returns an item of data corresponding to a specified model index.
1232
1233 Well behaved models also implement
1234 \l{QAbstractItemModel::headerData()}{headerData()} to give tree and
1235 table views something to display in their headers.
1236
1237 Note that this is a non-hierarchical model, so we don't have to worry
1238 about the parent-child relationships. If our model was hierarchical, we
1239 would also have to implement the
1240 \l{QAbstractItemModel::index()}{index()} and
1241 \l{QAbstractItemModel::parent()}{parent()} functions.
1242
1243 The list of strings is stored internally in the \c stringList private
1244 member variable.
1245
1246 \section3 Dimensions of the model
1247
1248 We want the number of rows in the model to be the same as the number of
1249 strings in the string list. We implement the
1250 \l{QAbstractItemModel::rowCount()}{rowCount()} function with this in
1251 mind:
1252
1253 \snippet doc/src/snippets/stringlistmodel/model.cpp 0
1254
1255 Since the model is non-hierarchical, we can safely ignore the model index
1256 corresponding to the parent item. By default, models derived from
1257 QAbstractListModel only contain one column, so we do not need to
1258 reimplement the \l{QAbstractItemModel::columnCount()}{columnCount()}
1259 function.
1260
1261 \section3 Model headers and data
1262
1263 For items in the view, we want to return the strings in the string list.
1264 The \l{QAbstractItemModel::data()}{data()} function is responsible for
1265 returning the item of data that corresponds to the index argument:
1266
1267 \snippet doc/src/snippets/stringlistmodel/model.cpp 1-data-read-only
1268
1269 We only return a valid QVariant if the model index supplied is valid,
1270 the row number is within the range of items in the string list, and the
1271 requested role is one that we support.
1272
1273 Some views, such as QTreeView and QTableView, are able to display headers
1274 along with the item data. If our model is displayed in a view with headers,
1275 we want the headers to show the row and column numbers. We can provide
1276 information about the headers by subclassing the
1277 \l{QAbstractItemModel::headerData()}{headerData()} function:
1278
1279 \snippet doc/src/snippets/stringlistmodel/model.cpp 2
1280
1281 Again, we return a valid QVariant only if the role is one that we support.
1282 The orientation of the header is also taken into account when deciding the
1283 exact data to return.
1284
1285 Not all views display headers with the item data, and those that do may
1286 be configured to hide them. Nonetheless, it is recommended that you
1287 implement the \l{QAbstractItemModel::headerData()}{headerData()} function
1288 to provide relevant information about the data provided by the model.
1289
1290 An item can have several roles, giving out different data depending on the
1291 role specified. The items in our model only have one role,
1292 \l{Qt::ItemDataRole}{DisplayRole}, so we return the data
1293 for items irrespective of the role specified.
1294 However, we could reuse the data we provide for the
1295 \l{Qt::ItemDataRole}{DisplayRole} in
1296 other roles, such as the
1297 \l{Qt::ItemDataRole}{ToolTipRole} that views can use to
1298 display information about items in a tooltip.
1299
1300 \section2 An editable model
1301
1302 The read-only model shows how simple choices could be presented to the
1303 user but, for many applications, an editable list model is much more
1304 useful. We can modify the read-only model to make the items editable
1305 by changing the data() function we implemented for read-only, and
1306 by implementing two extra functions:
1307 \l{QAbstractItemModel::flags()}{flags()} and
1308 \l{QAbstractItemModel::setData()}{setData()}.
1309 The following function declarations are added to the class definition:
1310
1311 \snippet doc/src/snippets/stringlistmodel/model.h 2
1312 \snippet doc/src/snippets/stringlistmodel/model.h 3
1313
1314 \section3 Making the model editable
1315
1316 A delegate checks whether an item is editable before creating an
1317 editor. The model must let the delegate know that its items are
1318 editable. We do this by returning the correct flags for each item in
1319 the model; in this case, we enable all items and make them both
1320 selectable and editable:
1321
1322 \snippet doc/src/snippets/stringlistmodel/model.cpp 3
1323
1324 Note that we do not have to know how the delegate performs the actual
1325 editing process. We only have to provide a way for the delegate to set the
1326 data in the model. This is achieved through the
1327 \l{QAbstractItemModel::setData()}{setData()} function:
1328
1329 \snippet doc/src/snippets/stringlistmodel/model.cpp 4
1330 \snippet doc/src/snippets/stringlistmodel/model.cpp 5
1331
1332 In this model, the item in the string list that corresponds to the
1333 model index is replaced by the value provided. However, before we
1334 can modify the string list, we must make sure that the index is
1335 valid, the item is of the correct type, and that the role is
1336 supported. By convention, we insist that the role is the
1337 \l{Qt::ItemDataRole}{EditRole} since this is the role used by the
1338 standard item delegate. For boolean values, however, you can use
1339 Qt::CheckStateRole and set the Qt::ItemIsUserCheckable flag; a
1340 checkbox is then used for editing the value. The underlying
1341 data in this model is the same for all roles, so this detail just
1342 makes it easier to integrate the model with standard components.
1343
1344 When the data has been set, the model must let the views know that some
1345 data has changed. This is done by emitting the
1346 \l{QAbstractItemModel::dataChanged()}{dataChanged()} signal. Since only
1347 one item of data has changed, the range of items specified in the signal
1348 is limited to just one model index.
1349
1350 Also the data() function needs to be changed to add the Qt::EditRole test:
1351
1352 \snippet doc/src/snippets/stringlistmodel/model.cpp 1
1353
1354 \section3 Inserting and removing rows
1355
1356 It is possible to change the number of rows and columns in a model. In the
1357 string list model it only makes sense to change the number of rows, so we
1358 only reimplement the functions for inserting and removing rows. These are
1359 declared in the class definition:
1360
1361 \snippet doc/src/snippets/stringlistmodel/model.h 4
1362
1363 Since rows in this model correspond to strings in a list, the
1364 \c insertRows() function inserts a number of empty strings into the string
1365 list before the specified position. The number of strings inserted is
1366 equivalent to the number of rows specified.
1367
1368 The parent index is normally used to determine where in the model the
1369 rows should be added. In this case, we only have a single top-level list
1370 of strings, so we just insert empty strings into that list.
1371
1372 \snippet doc/src/snippets/stringlistmodel/model.cpp 6
1373 \snippet doc/src/snippets/stringlistmodel/model.cpp 7
1374
1375 The model first calls the
1376 \l{QAbstractItemModel::beginInsertRows()}{beginInsertRows()} function to
1377 inform other components that the number of rows is about to change. The
1378 function specifies the row numbers of the first and last new rows to be
1379 inserted, and the model index for their parent item. After changing the
1380 string list, it calls
1381 \l{QAbstractItemModel::endInsertRows()}{endInsertRows()} to complete the
1382 operation and inform other components that the dimensions of the model
1383 have changed, returning true to indicate success.
1384
1385 The function to remove rows from the model is also simple to write.
1386 The rows to be removed from the model are specified by the position and
1387 the number of rows given.
1388 We ignore the parent index to simplify our implementation, and just
1389 remove the corresponding items from the string list.
1390
1391 \snippet doc/src/snippets/stringlistmodel/model.cpp 8
1392 \snippet doc/src/snippets/stringlistmodel/model.cpp 9
1393
1394 The \l{QAbstractItemModel::beginRemoveRows()}{beginRemoveRows()} function
1395 is always called before any underlying data is removed, and specifies the
1396 first and last rows to be removed. This allows other components to access
1397 the data before it becomes unavailable.
1398 After the rows have been removed, the model emits
1399 \l{QAbstractItemModel::endRemoveRows()}{endRemoveRows()} to finish the
1400 operation and let other components know that the dimensions of the model
1401 have changed.
1402
1403 \section2 Next steps
1404
1405 We can display the data provided by this model, or any other model, using
1406 the \l QListView class to present the model's items in the form of a vertical
1407 list.
1408 For the string list model, this view also provides a default editor so that
1409 the items can be manipulated. We examine the possibilities made available by
1410 the standard view classes in \l{View Classes}.
1411
1412 The \l{Model Subclassing Reference} document discusses the requirements of
1413 QAbstractItemModel subclasses in more detail, and provides a guide to the
1414 virtual functions that must be implemented to enable various features in
1415 different types of models.
1416
1417 \section1 Item view convenience classes
1418
1419 Qt 4 also introduced some standard widgets to provide classic
1420 item-based container widgets. These behave in a similar way to the
1421 item view classes in Qt 3, but have been rewritten to use the
1422 underlying model/view framework for performance and
1423 maintainability. The old item view classes are still available in
1424 the compatibility library (see the \l{porting4.html}{Porting
1425 Guide} for more information).
1426
1427 The item-based widgets have been given names which reflect their uses:
1428 \c QListWidget provides a list of items, \c QTreeWidget displays a
1429 multi-level tree structure, and \c QTableWidget provides a table of cell
1430 items. Each class inherits the behavior of the \c QAbstractItemView
1431 class which implements common behavior for item selection and header
1432 management.
1433
1434 \section2 List widgets
1435
1436 Single level lists of items are typically displayed using a \c QListWidget
1437 and a number of \c{QListWidgetItem}s. A list widget is constructed in the
1438 same way as any other widget:
1439
1440 \snippet doc/src/snippets/qlistwidget-using/mainwindow.cpp 0
1441
1442 List items can be added directly to the list widget when they are
1443 constructed:
1444
1445 \snippet doc/src/snippets/qlistwidget-using/mainwindow.cpp 3
1446
1447 They can also be constructed without a parent list widget and added to
1448 a list at some later time:
1449
1450 \snippet doc/src/snippets/qlistwidget-using/mainwindow.cpp 6
1451 \snippet doc/src/snippets/qlistwidget-using/mainwindow.cpp 7
1452
1453 Each item in a list can display a text label and an icon. The colors
1454 and font used to render the text can be changed to provide a customized
1455 appearance for items. Tooltips, status tips, and "What's
1456 This?" help are all easily configured to ensure that the list is properly
1457 integrated into the application.
1458
1459 \snippet doc/src/snippets/qlistwidget-using/mainwindow.cpp 8
1460
1461 By default, items in a list are presented in the order of their creation.
1462 Lists of items can be sorted according to the criteria given in
1463 \l{Qt::SortOrder} to produce a list of items that is sorted in forward or
1464 reverse alphabetical order:
1465
1466 \snippet doc/src/snippets/qlistwidget-using/mainwindow.cpp 4
1467 \snippet doc/src/snippets/qlistwidget-using/mainwindow.cpp 5
1468
1469 \section2 Tree widgets
1470
1471 Trees or hierarchical lists of items are provided by the \c QTreeWidget
1472 and \c QTreeWidgetItem classes. Each item in the tree widget can have
1473 child items of its own, and can display a number of columns of
1474 information. Tree widgets are created just like any other widget:
1475
1476 \snippet doc/src/snippets/qtreewidget-using/mainwindow.cpp 0
1477
1478 Before items can be added to the tree widget, the number of columns must
1479 be set. For example, we could define two columns, and create a header
1480 to provide labels at the top of each column:
1481
1482 \snippet doc/src/snippets/qtreewidget-using/mainwindow.cpp 1
1483 \snippet doc/src/snippets/qtreewidget-using/mainwindow.cpp 2
1484
1485 The easiest way to set up the labels for each section is to supply a string
1486 list. For more sophisticated headers, you can construct a tree item,
1487 decorate it as you wish, and use that as the tree widget's header.
1488
1489 Top-level items in the tree widget are constructed with the tree widget as
1490 their parent widget. They can be inserted in an arbitrary order, or you
1491 can ensure that they are listed in a particular order by specifying the
1492 previous item when constructing each item:
1493
1494 \snippet doc/src/snippets/qtreewidget-using/mainwindow.cpp 3
1495 \codeline
1496 \snippet doc/src/snippets/qtreewidget-using/mainwindow.cpp 4
1497
1498 Tree widgets deal with top-level items slightly differently to other
1499 items from deeper within the tree. Items can be removed from the top
1500 level of the tree by calling the tree widget's
1501 \l{QTreeWidget::takeTopLevelItem()}{takeTopLevelItem()} function, but
1502 items from lower levels are removed by calling their parent item's
1503 \l{QTreeWidgetItem::takeChild()}{takeChild()} function.
1504 Items are inserted in the top level of the tree with the
1505 \l{QTreeWidget::insertTopLevelItem()}{insertTopLevelItem()} function.
1506 At lower levels in the tree, the parent item's
1507 \l{QTreeWidgetItem::insertChild()}{insertChild()} function is used.
1508
1509 It is easy to move items around between the top level and lower levels
1510 in the tree. We just need to check whether the items are top-level items
1511 or not, and this information is supplied by each item's \c parent()
1512 function. For example, we can remove the current item in the tree widget
1513 regardless of its location:
1514
1515 \snippet doc/src/snippets/qtreewidget-using/mainwindow.cpp 10
1516 \snippet doc/src/snippets/qtreewidget-using/mainwindow.cpp 11
1517
1518 Inserting the item somewhere else in the tree widget follows the same
1519 pattern:
1520
1521 \snippet doc/src/snippets/qtreewidget-using/mainwindow.cpp 8
1522 \snippet doc/src/snippets/qtreewidget-using/mainwindow.cpp 9
1523
1524 \section2 Table widgets
1525
1526 Tables of items similar to those found in spreadsheet applications
1527 are constructed with the \c QTableWidget and \c QTableWidgetItem. These
1528 provide a scrolling table widget with headers and items to use within it.
1529
1530 Tables can be created with a set number of rows and columns, or these
1531 can be added to an unsized table as they are needed.
1532
1533 \snippet doc/src/snippets/qtablewidget-using/mainwindow.h 0
1534 \snippet doc/src/snippets/qtablewidget-using/mainwindow.cpp 0
1535
1536 Items are constructed outside the table before being added to the table
1537 at the required location:
1538
1539 \snippet doc/src/snippets/qtablewidget-using/mainwindow.cpp 3
1540
1541 Horizontal and vertical headers can be added to the table by constructing
1542 items outside the table and using them as headers:
1543
1544 \snippet doc/src/snippets/qtablewidget-using/mainwindow.cpp 1
1545
1546 Note that the rows and columns in the table begin at zero.
1547
1548 \section2 Common features
1549
1550 There are a number of item-based features common to each of the
1551 convenience classes that are available through the same interfaces
1552 in each class. We present these in the following sections with some
1553 examples for different widgets.
1554 Look at the list of \l{Model/View Classes} for each of the widgets
1555 for more details about the use of each function used.
1556
1557 \section3 Hidden items
1558
1559 It is sometimes useful to be able to hide items in an item view widget
1560 rather than remove them. Items for all of the above widgets can be
1561 hidden and later shown again. You can determine whether an item is hidden
1562 by calling the isItemHidden() function, and items can be hidden with
1563 \c setItemHidden().
1564
1565 Since this operation is item-based, the same function is available for
1566 all three convenience classes.
1567
1568 \section3 Selections
1569
1570 The way items are selected is controlled by the widget's selection mode
1571 (\l{QAbstractItemView::SelectionMode}).
1572 This property controls whether the user can select one or many items and,
1573 in many-item selections, whether the selection must be a continuous range
1574 of items. The selection mode works in the same way for all of the
1575 above widgets.
1576
1577 \table
1578 \row
1579 \i \img selection-single.png
1580 \i \bold{Single item selections:}
1581 Where the user needs to choose a single item from a widget, the
1582 default \c SingleSelection mode is most suitable. In this mode, the
1583 current item and the selected item are the same.
1584
1585 \row
1586 \i \img selection-multi.png
1587 \i \bold{Multi-item selections:}
1588 In this mode, the user can toggle the selection state of any item in the
1589 widget without changing the existing selection, much like the way
1590 non-exclusive checkboxes can be toggled independently.
1591
1592 \row
1593 \i \img selection-extended.png
1594 \i \bold{Extended selections:}
1595 Widgets that often require many adjacent items to be selected, such
1596 as those found in spreadsheets, require the \c ExtendedSelection mode.
1597 In this mode, continuous ranges of items in the widget can be selected
1598 with both the mouse and the keyboard.
1599 Complex selections, involving many items that are not adjacent to other
1600 selected items in the widget, can also be created if modifier keys are
1601 used.
1602
1603 If the user selects an item without using a modifier key, the existing
1604 selection is cleared.
1605 \endtable
1606
1607 The selected items in a widget are read using the \c selectedItems()
1608 function, providing a list of relevant items that can be iterated over.
1609 For example, we can find the sum of all the numeric values within a
1610 list of selected items with the following code:
1611
1612 \snippet doc/src/snippets/qtablewidget-using/mainwindow.cpp 4
1613
1614 Note that for the single selection mode, the current item will be in
1615 the selection. In the multi-selection and extended selection modes, the
1616 current item may not lie within the selection, depending on the way the
1617 user formed the selection.
1618
1619 \section3 Searching
1620
1621 It is often useful to be able to find items within an item view widget,
1622 either as a developer or as a service to present to users. All three
1623 item view convenience classes provide a common \c findItems() function
1624 to make this as consistent and simple as possible.
1625
1626 Items are searched for by the text that they contain according to
1627 criteria specified by a selection of values from Qt::MatchFlags.
1628 We can obtain a list of matching items with the \c findItems()
1629 function:
1630
1631 \snippet doc/src/snippets/qtreewidget-using/mainwindow.cpp 6
1632 \snippet doc/src/snippets/qtreewidget-using/mainwindow.cpp 7
1633
1634 The above code causes items in a tree widget to be selected if they
1635 contain the text given in the search string. This pattern can also be
1636 used in the list and table widgets.
1637
1638 \section1 Using Drag and Drop with Item Views
1639
1640 Qt's drag and drop infrastructure is fully supported by the model/view framework.
1641 Items in lists, tables, and trees can be dragged within the views, and data can be
1642 imported and exported as MIME-encoded data.
1643
1644 The standard views automatically support internal drag and drop, where items are
1645 moved around to change the order in which they are displayed. By default, drag and
1646 drop is not enabled for these views because they are configured for the simplest,
1647 most common uses. To allow items to be dragged around, certain properties of the
1648 view need to be enabled, and the items themselves must also allow dragging to occur.
1649
1650 The requirements for a model that only allows items to be exported from a
1651 view, and which does not allow data to be dropped into it, are fewer than
1652 those for a fully-enabled drag and drop model.
1653
1654 See also the \l{Model Subclassing Reference} for more information about
1655 enabling drag and drop support in new models.
1656
1657 \section2 Using convenience views
1658
1659 Each of the types of item used with QListWidget, QTableWidget, and QTreeWidget
1660 is configured to use a different set of flags by default. For example, each
1661 QListWidgetItem or QTreeWidgetItem is initially enabled, checkable, selectable,
1662 and can be used as the source of a drag and drop operation; each QTableWidgetItem
1663 can also be edited and used as the target of a drag and drop operation.
1664
1665 Although all of the standard items have one or both flags set for drag and drop,
1666 you generally need to set various properties in the view itself to take advantage
1667 of the built-in support for drag and drop:
1668
1669 \list
1670 \o To enable item dragging, set the view's
1671 \l{QAbstractItemView::dragEnabled}{dragEnabled} property to \c true.
1672 \o To allow the user to drop either internal or external items within the view,
1673 set the view's \l{QAbstractScrollArea::}{viewport()}'s
1674 \l{QWidget::acceptDrops}{acceptDrops} property to \c true.
1675 \o To show the user where the item currently being dragged will be placed if
1676 dropped, set the view's \l{QAbstractItemView::showDropIndicator}{showDropIndicator}
1677 property. This provides the user with continuously updating information about
1678 item placement within the view.
1679 \endlist
1680
1681 For example, we can enable drag and drop in a list widget with the following lines
1682 of code:
1683
1684 \snippet doc/src/snippets/qlistwidget-dnd/mainwindow.cpp 0
1685
1686 The result is a list widget which allows the items to be copied
1687 around within the view, and even lets the user drag items between
1688 views containing the same type of data. In both situations, the
1689 items are copied rather than moved.
1690
1691 To enable the user to move the items around within the view, we
1692 must set the list widget's \l {QAbstractItemView::}{dragDropMode}:
1693
1694 \snippet doc/src/snippets/qlistwidget-dnd/mainwindow.cpp 1
1695
1696 \section2 Using model/view classes
1697
1698 Setting up a view for drag and drop follows the same pattern used with the
1699 convenience views. For example, a QListView can be set up in the same way as a
1700 QListWidget:
1701
1702 \snippet doc/src/snippets/qlistview-dnd/mainwindow.cpp 0
1703
1704 Since access to the data displayed by the view is controlled by a model, the
1705 model used also has to provide support for drag and drop operations. The
1706 actions supported by a model can be specified by reimplementing the
1707 QAbstractItemModel::supportedDropActions() function. For example, copy and
1708 move operations are enabled with the following code:
1709
1710 \snippet doc/src/snippets/qlistview-dnd/model.cpp 10
1711
1712 Although any combination of values from Qt::DropActions can be given, the
1713 model needs to be written to support them. For example, to allow Qt::MoveAction
1714 to be used properly with a list model, the model must provide an implementation
1715 of QAbstractItemModel::removeRows(), either directly or by inheriting the
1716 implementation from its base class.
1717
1718 \section3 Enabling drag and drop for items
1719
1720 Models indicate to views which items can be dragged, and which will accept drops,
1721 by reimplementing the QAbstractItemModel::flags() function to provide suitable
1722 flags.
1723
1724 For example, a model which provides a simple list based on QAbstractListModel
1725 can enable drag and drop for each of the items by ensuring that the flags
1726 returned contain the \l Qt::ItemIsDragEnabled and \l Qt::ItemIsDropEnabled
1727 values:
1728
1729 \snippet doc/src/snippets/qlistview-dnd/model.cpp 7
1730
1731 Note that items can be dropped into the top level of the model, but dragging is
1732 only enabled for valid items.
1733
1734 In the above code, since the model is derived from QStringListModel, we
1735 obtain a default set of flags by calling its implementation of the flags()
1736 function.
1737
1738 \section3 Encoding exported data
1739
1740 When items of data are exported from a model in a drag and drop operation, they
1741 are encoded into an appropriate format corresponding to one or more MIME types.
1742 Models declare the MIME types that they can use to supply items by reimplementing
1743 the QAbstractItemModel::mimeTypes() function, returning a list of standard MIME
1744 types.
1745
1746 For example, a model that only provides plain text would provide the following
1747 implementation:
1748
1749 \snippet doc/src/snippets/qlistview-dnd/model.cpp 9
1750
1751 The model must also provide code to encode data in the advertised format. This
1752 is achieved by reimplementing the QAbstractItemModel::mimeData() function to
1753 provide a QMimeData object, just as in any other drag and drop operation.
1754
1755 The following code shows how each item of data, corresponding to a given list of
1756 indexes, is encoded as plain text and stored in a QMimeData object.
1757
1758 \snippet doc/src/snippets/qlistview-dnd/model.cpp 8
1759
1760 Since a list of model indexes is supplied to the function, this approach is general
1761 enough to be used in both hierarchical and non-heirarchical models.
1762
1763 Note that custom datatypes must be declared as \l{QMetaObject}{meta objects}
1764 and that stream operators must be implemented for them. See the QMetaObject
1765 class description for details.
1766
1767 \section3 Inserting dropped data into a model
1768
1769 The way that any given model handles dropped data depends on both its type
1770 (list, table, or tree) and the way its contents is likely to be presented to
1771 the user. Generally, the approach taken to accommodate dropped data should
1772 be the one that most suits the model's underlying data store.
1773
1774 Different types of model tend to handle dropped data in different ways. List
1775 and table models only provide a flat structure in which items of data are
1776 stored. As a result, they may insert new rows (and columns) when data is
1777 dropped on an existing item in a view, or they may overwrite the item's
1778 contents in the model using some of the data supplied. Tree models are
1779 often able to add child items containing new data to their underlying data
1780 stores, and will therefore behave more predictably as far as the user
1781 is concerned.
1782
1783 Dropped data is handled by a model's reimplementation of
1784 QAbstractItemModel::dropMimeData(). For example, a model that handles a
1785 simple list of strings can provide an implementation that handles data
1786 dropped onto existing items separately to data dropped into the top level
1787 of the model (i.e., onto an invalid item).
1788
1789 The model first has to make sure that the operation should be acted on,
1790 the data supplied is in a format that can be used, and that its destination
1791 within the model is valid:
1792
1793 \snippet doc/src/snippets/qlistview-dnd/model.cpp 0
1794 \snippet doc/src/snippets/qlistview-dnd/model.cpp 1
1795
1796 A simple one column string list model can indicate failure if the data
1797 supplied is not plain text, or if the column number given for the drop
1798 is invalid.
1799
1800 The data to be inserted into the model is treated differently depending on
1801 whether it is dropped onto an existing item or not. In this simple example,
1802 we want to allow drops between existing items, before the first item in the
1803 list, and after the last item.
1804
1805 When a drop occurs, the model index corresponding to the parent item will
1806 either be valid, indicating that the drop occurred on an item, or it will
1807 be invalid, indicating that the drop occurred somewhere in the view that
1808 corresponds to top level of the model.
1809
1810 \snippet doc/src/snippets/qlistview-dnd/model.cpp 2
1811
1812 We initially examine the row number supplied to see if we can use it
1813 to insert items into the model, regardless of whether the parent index is
1814 valid or not.
1815
1816 \snippet doc/src/snippets/qlistview-dnd/model.cpp 3
1817
1818 If the parent model index is valid, the drop occurred on an item. In this
1819 simple list model, we find out the row number of the item and use that
1820 value to insert dropped items into the top level of the model.
1821
1822 \snippet doc/src/snippets/qlistview-dnd/model.cpp 4
1823
1824 When a drop occurs elsewhere in the view, and the row number is unusable,
1825 we append items to the top level of the model.
1826
1827 In hierarchical models, when a drop occurs on an item, it would be better to
1828 insert new items into the model as children of that item. In the simple
1829 example shown here, the model only has one level, so this approach is not
1830 appropriate.
1831
1832 \section3 Decoding imported data
1833
1834 Each implementation of \l{QAbstractItemModel::dropMimeData()}{dropMimeData()} must
1835 also decode the data and insert it into the model's underlying data structure.
1836
1837 For a simple string list model, the encoded items can be decoded and streamed
1838 into a QStringList:
1839
1840 \snippet doc/src/snippets/qlistview-dnd/model.cpp 5
1841
1842 The strings can then be inserted into the underlying data store. For consistency,
1843 this can be done through the model's own interface:
1844
1845 \snippet doc/src/snippets/qlistview-dnd/model.cpp 6
1846
1847 Note that the model will typically need to provide implementations of the
1848 QAbstractItemModel::insertRows() and QAbstractItemModel::setData() functions.
1849
1850 \sa {Item Views Puzzle Example}
1851
1852 \section1 Proxy models
1853
1854 In the model/view framework, items of data supplied by a single model can be shared
1855 by any number of views, and each of these can possibly represent the same information
1856 in completely different ways.
1857 Custom views and delegates are effective ways to provide radically different
1858 representations of the same data. However, applications often need to provide
1859 conventional views onto processed versions of the same data, such as differently-sorted
1860 views onto a list of items.
1861
1862 Although it seems appropriate to perform sorting and filtering operations as internal
1863 functions of views, this approach does not allow multiple views to share the results
1864 of such potentially costly operations. The alternative approach, involving sorting
1865 within the model itself, leads to the similar problem where each view has to display
1866 items of data that are organized according to the most recent processing operation.
1867
1868 To solve this problem, the model/view framework uses proxy models to manage the
1869 information supplied between individual models and views. Proxy models are components
1870 that behave like ordinary models from the perspective of a view, and access data from
1871 source models on behalf of that view. The signals and slots used by the model/view
1872 framework ensure that each view is updated appropriately no matter how many proxy models
1873 are placed between itself and the source model.
1874
1875 \section2 Using proxy models
1876
1877 Proxy models can be inserted between an existing model and any number of views.
1878 Qt is supplied with a standard proxy model, QSortFilterProxyModel, that is usually
1879 instantiated and used directly, but can also be subclassed to provide custom filtering
1880 and sorting behavior. The QSortFilterProxyModel class can be used in the following way:
1881
1882 \snippet doc/src/snippets/qsortfilterproxymodel/main.cpp 0
1883 \codeline
1884 \snippet doc/src/snippets/qsortfilterproxymodel/main.cpp 1
1885
1886 Since proxy models are inherit from QAbstractItemModel, they can be connected to
1887 any kind of view, and can be shared between views. They can also be used to
1888 process the information obtained from other proxy models in a pipeline arrangement.
1889
1890 The QSortFilterProxyModel class is designed to be instantiated and used directly
1891 in applications. More specialized proxy models can be created by subclassing this
1892 classes and implementing the required comparison operations.
1893
1894 \section2 Customizing proxy models
1895
1896 Generally, the type of processing used in a proxy model involves mapping each item of
1897 data from its original location in the source model to either a different location in
1898 the proxy model. In some models, some items may have no corresponding location in the
1899 proxy model; these models are \e filtering proxy models. Views access items using
1900 model indexes provided by the proxy model, and these contain no information about the
1901 source model or the locations of the original items in that model.
1902
1903 QSortFilterProxyModel enables data from a source model to be filtered before
1904 being supplied to views, and also allows the contents of a source model to
1905 be supplied to views as pre-sorted data.
1906
1907 \section3 Custom filtering models
1908
1909 The QSortFilterProxyModel class provides a filtering model that is fairly versatile,
1910 and which can be used in a variety of common situations. For advanced users,
1911 QSortFilterProxyModel can be subclassed, providing a mechanism that enables custom
1912 filters to be implemented.
1913
1914 Subclasses of QSortFilterProxyModel can reimplement two virtual functions that are
1915 called whenever a model index from the proxy model is requested or used:
1916
1917 \list
1918 \o \l{QSortFilterProxyModel::filterAcceptsColumn()}{filterAcceptsColumn()} is used to
1919 filter specific columns from part of the source model.
1920 \o \l{QSortFilterProxyModel::filterAcceptsRow()}{filterAcceptsRow()} is used to filter
1921 specific rows from part of the source model.
1922 \endlist
1923
1924 The default implementations of the above functions in QSortFilterProxyModel
1925 return true to ensure that all items are passed through to views; reimplementations
1926 of these functions should return false to filter out individual rows and columns.
1927
1928 \section3 Custom sorting models
1929
1930 QSortFilterProxyModel instances use Qt's built-in qStableSort() function to set up
1931 mappings between items in the source model and those in the proxy model, allowing a
1932 sorted hierarchy of items to be exposed to views without modifying the structure of the
1933 source model. To provide custom sorting behavior, reimplement the
1934 \l{QSortFilterProxyModel::lessThan()}{lessThan()} function to perform custom
1935 comparisons.
1936
1937 \section1 Model subclassing reference
1938
1939 Model subclasses need to provide implementations of many of the virtual functions
1940 defined in the QAbstractItemModel base class. The number of these functions that need
1941 to be implemented depends on the type of model - whether it supplies views with
1942 a simple list, a table, or a complex hierarchy of items. Models that inherit from
1943 QAbstractListModel and QAbstractTableModel can take advantage of the default
1944 implementations of functions provided by those classes. Models that expose items
1945 of data in tree-like structures must provide implementations for many of the
1946 virtual functions in QAbstractItemModel.
1947
1948 The functions that need to be implemented in a model subclass can be divided into three
1949 groups:
1950
1951 \list
1952 \o \bold{Item data handling:} All models need to implement functions to enable views and
1953 delegates to query the dimensions of the model, examine items, and retrieve data.
1954 \o \bold{Navigation and index creation:} Hierarchical models need to provide functions
1955 that views can call to navigate the tree-like structures they expose, and obtain
1956 model indexes for items.
1957 \o \bold{Drag and drop support and MIME type handling:} Models inherit functions that
1958 control the way that internal and external drag and drop operations are performed.
1959 These functions allow items of data to be described in terms of MIME types that
1960 other components and applications can understand.
1961 \endlist
1962
1963 For more information, see the \l
1964 {"Item View Classes" Chapter of C++ GUI Programming with Qt 4}.
1965
1966 \section2 Item data handling
1967
1968 Models can provide varying levels of access to the data they provide: They can be
1969 simple read-only components, some models may support resizing operations, and
1970 others may allow items to be edited.
1971
1972 \section2 Read-Only access
1973
1974 To provide read-only access to data provided by a model, the following functions
1975 \e{must} be implemented in the model's subclass:
1976
1977 \table 90%
1978 \row \o \l{QAbstractItemModel::flags()}{flags()}
1979 \o Used by other components to obtain information about each item provided by
1980 the model. In many models, the combination of flags should include
1981 Qt::ItemIsEnabled and Qt::ItemIsSelectable.
1982 \row \o \l{QAbstractItemModel::data()}{data()}
1983 \o Used to supply item data to views and delegates. Generally, models only
1984 need to supply data for Qt::DisplayRole and any application-specific user
1985 roles, but it is also good practice to provide data for Qt::ToolTipRole,
1986 Qt::AccessibleTextRole, and Qt::AccessibleDescriptionRole.
1987 See the Qt::ItemDataRole enum documentation for information about the types
1988 associated with each role.
1989 \row \o \l{QAbstractItemModel::headerData()}{headerData()}
1990 \o Provides views with information to show in their headers. The information is
1991 only retrieved by views that can display header information.
1992 \row \o \l{QAbstractItemModel::rowCount()}{rowCount()}
1993 \o Provides the number of rows of data exposed by the model.
1994 \endtable
1995
1996 These four functions must be implemented in all types of model, including list models
1997 (QAbstractListModel subclasses) and table models (QAbstractTableModel subclasses).
1998
1999 Additionally, the following functions \e{must} be implemented in direct subclasses
2000 of QAbstractTableModel and QAbstractItemModel:
2001
2002 \table 90%
2003 \row \o \l{QAbstractItemModel::columnCount()}{columnCount()}
2004 \o Provides the number of columns of data exposed by the model. List models do not
2005 provide this function because it is already implemented in QAbstractListModel.
2006 \endtable
2007
2008 \section3 Editable items
2009
2010 Editable models allow items of data to be modified, and may also provide
2011 functions to allow rows and columns to be inserted and removed. To enable
2012 editing, the following functions must be implemented correctly:
2013
2014 \table 90%
2015 \row \o \l{QAbstractItemModel::flags()}{flags()}
2016 \o Must return an appropriate combination of flags for each item. In particular,
2017 the value returned by this function must include \l{Qt::ItemIsEditable} in
2018 addition to the values applied to items in a read-only model.
2019 \row \o \l{QAbstractItemModel::setData()}{setData()}
2020 \o Used to modify the item of data associated with a specified model index.
2021 To be able to accept user input, provided by user interface elements, this
2022 function must handle data associated with Qt::EditRole.
2023 The implementation may also accept data associated with many different kinds
2024 of roles specified by Qt::ItemDataRole. After changing the item of data,
2025 models must emit the \l{QAbstractItemModel::dataChanged()}{dataChanged()}
2026 signal to inform other components of the change.
2027 \row \o \l{QAbstractItemModel::setHeaderData()}{setHeaderData()}
2028 \o Used to modify horizontal and vertical header information. After changing
2029 the item of data, models must emit the
2030 \l{QAbstractItemModel::headerDataChanged()}{headerDataChanged()}
2031 signal to inform other components of the change.
2032 \endtable
2033
2034 \section3 Resizable models
2035
2036 All types of model can support the insertion and removal of rows. Table models
2037 and hierarchical models can also support the insertion and removal of columns.
2038 It is important to notify other components about changes to the model's dimensions
2039 both \e before and \e after they occur. As a result, the following functions
2040 can be implemented to allow the model to be resized, but implementations must
2041 ensure that the appropriate functions are called to notify attached views and
2042 delegates:
2043
2044 \table 90%
2045 \row \o \l{QAbstractItemModel::insertRows()}{insertRows()}
2046 \o Used to add new rows and items of data to all types of model.
2047 Implementations must call
2048 \l{QAbstractItemModel::beginInsertRows()}{beginInsertRows()} \e before
2049 inserting new rows into any underlying data structures, and call
2050 \l{QAbstractItemModel::endInsertRows()}{endInsertRows()}
2051 \e{immediately afterwards}.
2052 \row \o \l{QAbstractItemModel::removeRows()}{removeRows()}
2053 \o Used to remove rows and the items of data they contain from all types of model.
2054 Implementations must call
2055 \l{QAbstractItemModel::beginRemoveRows()}{beginRemoveRows()}
2056 \e before inserting new columns into any underlying data structures, and call
2057 \l{QAbstractItemModel::endRemoveRows()}{endRemoveRows()}
2058 \e{immediately afterwards}.
2059 \row \o \l{QAbstractItemModel::insertColumns()}{insertColumns()}
2060 \o Used to add new columns and items of data to table models and hierarchical models.
2061 Implementations must call
2062 \l{QAbstractItemModel::beginInsertColumns()}{beginInsertColumns()} \e before
2063 rows are removed from any underlying data structures, and call
2064 \l{QAbstractItemModel::endInsertColumns()}{endInsertColumns()}
2065 \e{immediately afterwards}.
2066 \row \o \l{QAbstractItemModel::removeColumns()}{removeColumns()}
2067 \o Used to remove columns and the items of data they contain from table models and
2068 hierarchical models.
2069 Implementations must call
2070 \l{QAbstractItemModel::beginRemoveColumns()}{beginRemoveColumns()}
2071 \e before columns are removed from any underlying data structures, and call
2072 \l{QAbstractItemModel::endRemoveColumns()}{endRemoveColumns()}
2073 \e{immediately afterwards}.
2074 \endtable
2075
2076 Generally, these functions should return true if the operation was successful.
2077 However, there may be cases where the operation only partly succeeded; for example,
2078 if less than the specified number of rows could be inserted. In such cases, the
2079 model should return false to indicate failure to enable any attached components to
2080 handle the situation.
2081
2082 The signals emitted by the functions called in implementations of the resizing
2083 API give attached components the chance to take action before any data becomes
2084 unavailable. The encapsulation of insert and remove operations with begin and end
2085 functions also enable the model to manage
2086 \l{QPersistentModelIndex}{persistent model indexes} correctly.
2087
2088 Normally, the begin and end functions are capable of informing other components
2089 about changes to the model's underlying structure. For more complex changes to the
2090 model's structure, perhaps involving internal reorganization or sorting of data,
2091 it is necessary to emit the \l{QAbstractItemModel::layoutChanged()}{layoutChanged()}
2092 signal to cause any attached views to be updated.
2093
2094 \section3 Lazy population of model data
2095
2096 Lazy population of model data effectively allows requests for information
2097 about the model to be deferred until it is actually needed by views.
2098
2099 Some models need to obtain data from remote sources, or must perform
2100 time-consuming operations to obtain information about the way the
2101 data is organized. Since views generally request as much information
2102 as possible in order to accurately display model data, it can be useful
2103 to restrict the amount of information returned to them to reduce
2104 unnecessary follow-up requests for data.
2105
2106 In hierarchical models where finding the number of children of a given
2107 item is an expensive operation, it is useful to ensure that the model's
2108 \l{QAbstractItemModel::}{rowCount()} implementation is only called when
2109 necessary. In such cases, the \l{QAbstractItemModel::}{hasChildren()}
2110 function can be reimplemented to provide an inexpensive way for views to
2111 check for the presence of children and, in the case of QTreeView, draw
2112 the appropriate decoration for their parent item.
2113
2114 Whether the reimplementation of \l{QAbstractItemModel::}{hasChildren()}
2115 returns \c true or \c false, it may not be necessary for the view to call
2116 \l{QAbstractItemModel::}{rowCount()} to find out how many children are
2117 present. For example, QTreeView does not need to know how many children
2118 there are if the parent item has not been expanded to show them.
2119
2120 If it is known that many items will have children, reimplementing
2121 \l{QAbstractItemModel::}{hasChildren()} to unconditionally return \c true
2122 is sometimes a useful approach to take. This ensures that each item can
2123 be later examined for children while making initial population of model
2124 data as fast as possible. The only disadvantage is that items without
2125 children may be displayed incorrectly in some views until the user
2126 attempts to view the non-existent child items.
2127
2128 \section2 Navigation and model index creation
2129
2130 Hierarchical models need to provide functions that views can call to navigate the
2131 tree-like structures they expose, and obtain model indexes for items.
2132
2133 \section3 Parents and children
2134
2135 Since the structure exposed to views is determined by the underlying data
2136 structure, it is up to each model subclass to create its own model indexes
2137 by providing implementations of the following functions:
2138
2139 \table 90%
2140 \row \o \l{QAbstractItemModel::index()}{index()}
2141 \o Given a model index for a parent item, this function allows views and delegates
2142 to access children of that item. If no valid child item - corresponding to the
2143 specified row, column, and parent model index, can be found, the function
2144 must return QModelIndex(), which is an invalid model index.
2145 \row \o \l{QAbstractItemModel::parent()}{parent()}
2146 \o Provides a model index corresponding to the parent of any given child item.
2147 If the model index specified corresponds to a top-level item in the model, or if
2148 there is no valid parent item in the model, the function must return
2149 an invalid model index, created with the empty QModelIndex() constructor.
2150 \endtable
2151
2152 Both functions above use the \l{QAbstractItemModel::createIndex()}{createIndex()}
2153 factory function to generate indexes for other components to use. It is normal for
2154 models to supply some unique identifier to this function to ensure that
2155 the model index can be re-associated with its corresponding item later on.
2156
2157 \section2 Drag and drop support and MIME type handling
2158
2159 The model/view classes support drag and drop operations, providing default behavior
2160 that is sufficient for many applications. However, it is also possible to customize
2161 the way items are encoded during drag and drop operations, whether they are copied
2162 or moved by default, and how they are inserted into existing models.
2163
2164 Additionally, the convenience view classes implement specialized behavior that
2165 should closely follow that expected by existing developers.
2166 The \l{#Convenience Views}{Convenience Views} section provides an overview of this
2167 behavior.
2168
2169 \section3 MIME data
2170
2171 By default, the built-in models and views use an internal MIME type
2172 (\c{application/x-qabstractitemmodeldatalist}) to pass around information about
2173 model indexes. This specifies data for a list of items, containing the row and
2174 column numbers of each item, and information about the roles that each item
2175 supports.
2176
2177 Data encoded using this MIME type can be obtained by calling
2178 QAbstractItemModel::mimeData() with a QModelIndexList containing the items to
2179 be serialized.
2180 \omit
2181 The following types are used to store information about
2182 each item as it is streamed into a QByteArray and stored in a QMimeData object:
2183
2184 \table 90%
2185 \header \o Description \o Type
2186 \row \o Row \o int
2187 \row \o Column \o int
2188 \row \o Data for each role \o QMap<int, QVariant>
2189 \endtable
2190
2191 This information can be retrieved for use in non-model classes by calling
2192 QMimeData::data() with the \c{application/x-qabstractitemmodeldatalist} MIME
2193 type and streaming out the items one by one.
2194 \endomit
2195
2196 When implementing drag and drop support in a custom model, it is possible to
2197 export items of data in specialized formats by reimplementing the following
2198 function:
2199
2200 \table 90%
2201 \row \o \l{QAbstractItemModel::mimeData()}{mimeData()}
2202 \o This function can be reimplemented to return data in formats other
2203 than the default \c{application/x-qabstractitemmodeldatalist} internal
2204 MIME type.
2205
2206 Subclasses can obtain the default QMimeData object from the base class
2207 and add data to it in additional formats.
2208 \endtable
2209
2210 For many models, it is useful to provide the contents of items in common format
2211 represented by MIME types such as \c{text/plain} and \c{image/png}. Note that
2212 images, colors and HTML documents can easily be added to a QMimeData object with
2213 the QMimeData::setImageData(), QMimeData::setColorData(), and
2214 QMimeData::setHtml() functions.
2215
2216 \section3 Accepting dropped data
2217
2218 When a drag and drop operation is performed over a view, the underlying model is
2219 queried to determine which types of operation it supports and the MIME types
2220 it can accept. This information is provided by the
2221 QAbstractItemModel::supportedDropActions() and QAbstractItemModel::mimeTypes()
2222 functions. Models that do not override the implementations provided by
2223 QAbstractItemModel support copy operations and the default internal MIME type
2224 for items.
2225
2226 When serialized item data is dropped onto a view, the data is inserted into
2227 the current model using its implementation of QAbstractItemModel::dropMimeData().
2228 The default implementation of this function will never overwrite any data in the
2229 model; instead, it tries to insert the items of data either as siblings of an
2230 item, or as children of that item.
2231
2232 To take advantage of QAbstractItemModel's default implementation for the built-in
2233 MIME type, new models must provide reimplementations of the following functions:
2234
2235 \table 90%
2236 \row \o \l{QAbstractItemModel::insertRows()}{insertRows()}
2237 \o {1, 2} These functions enable the model to automatically insert new data using
2238 the existing implementation provided by QAbstractItemModel::dropMimeData().
2239 \row \o \l{QAbstractItemModel::insertColumns()}{insertColumns()}
2240 \row \o \l{QAbstractItemModel::setData()}{setData()}
2241 \o Allows the new rows and columns to be populated with items.
2242 \row \o \l{QAbstractItemModel::setItemData()}{setItemData()}
2243 \o This function provides more efficient support for populating new items.
2244 \endtable
2245
2246 To accept other forms of data, these functions must be reimplemented:
2247
2248 \table 90%
2249 \row \o \l{QAbstractItemModel::supportedDropActions()}{supportedDropActions()}
2250 \o Used to return a combination of \l{Qt::DropActions}{drop actions},
2251 indicating the types of drag and drop operations that the model accepts.
2252 \row \o \l{QAbstractItemModel::mimeTypes()}{mimeTypes()}
2253 \o Used to return a list of MIME types that can be decoded and handled by
2254 the model. Generally, the MIME types that are supported for input into
2255 the model are the same as those that it can use when encoding data for
2256 use by external components.
2257 \row \o \l{QAbstractItemModel::dropMimeData()}{dropMimeData()}
2258 \o Performs the actual decoding of the data transferred by drag and drop
2259 operations, determines where in the model it will be set, and inserts
2260 new rows and columns where necessary. How this function is implemented
2261 in subclasses depends on the requirements of the data exposed by each
2262 model.
2263 \endtable
2264
2265 If the implementation of the \l{QAbstractItemModel::dropMimeData()}{dropMimeData()}
2266 function changes the dimensions of a model by inserting or removing rows or
2267 columns, or if items of data are modified, care must be taken to ensure that
2268 all relevant signals are emitted. It can be useful to simply call
2269 reimplementations of other functions in the subclass, such as
2270 \l{QAbstractItemModel::setData()}{setData()},
2271 \l{QAbstractItemModel::insertRows()}{insertRows()}, and
2272 \l{QAbstractItemModel::insertColumns()}{insertColumns()}, to ensure that the
2273 model behaves consistently.
2274
2275 In order to ensure drag operations work properly, it is important to
2276 reimplement the following functions that remove data from the model:
2277
2278 \list
2279 \o \l{QAbstractItemModel::}{removeRows()}
2280 \o \l{QAbstractItemModel::}{removeRow()}
2281 \o \l{QAbstractItemModel::}{removeColumns()}
2282 \o \l{QAbstractItemModel::}{removeColumn()}
2283 \endlist
2284
2285 For more information about drag and drop with item views, refer to
2286 \l{Using drag and drop with item views}.
2287
2288 \section3 Convenience views
2289
2290 The convenience views (QListWidget, QTableWidget, and QTreeWidget) override
2291 the default drag and drop functionality to provide less flexible, but more
2292 natural behavior that is appropriate for many applications. For example,
2293 since it is more common to drop data into cells in a QTableWidget, replacing
2294 the existing contents with the data being transferred, the underlying model
2295 will set the data of the target items rather than insert new rows and columns
2296 into the model. For more information on drag and drop in convenience views,
2297 you can see \l{Using drag and drop with item views}.
2298
2299 \section2 Performance optimization for large amounts of data
2300
2301 The \l{QAbstractItemModel::}{canFetchMore()} function checks if the parent
2302 has more data available and returns true or false accordingly. The
2303 \l{QAbstractItemModel::}{fetchMore()} function fetches data based on the
2304 parent specified. Both these functions can be combined, for example, in a
2305 database query involving incremental data to populate a QAbstractItemModel.
2306 We reimplement \l{QAbstractItemModel::}{canFetchMore()} to indicate if there
2307 is more data to be fetched and \l{QAbstractItemModel::}{fetchMore()} to
2308 populate the model as required.
2309
2310 Another example would be dynamically populated tree models, where we
2311 reimplement \l{QAbstractItemModel::}{fetchMore()} when a branch in the tree
2312 model is expanded.
2313
2314 If your reimplementation of \l{QAbstractItemModel::}{fetchMore()} adds rows
2315 to the model, you need to call \l{QAbstractItemModel::}{beginInsertRows()}
2316 and \l{QAbstractItemModel::}{endInsertRows()}. Also, both
2317 \l{QAbstractItemModel::}{canFetchMore()} and \l{QAbstractItemModel::}
2318 {fetchMore()} must be reimplemented as their default implementation returns
2319 false and does nothing.
2320
2321 \keyword Model/View Classes
2322 \section1 The model/view classes
2323
2324 These classes use the model/view design pattern in which the
2325 underlying data (in the model) is kept separate from the way the
2326 data is presented and manipulated by the user (in the view).
2327
2328 \annotatedlist model-view
2329
2330 \section1 Related examples
2331
2332 \list
2333 \o \l{itemviews/dirview}{Dir View}
2334 \o \l{itemviews/spinboxdelegate}{Spin Box Delegate}
2335 \o \l{itemviews/pixelator}{Pixelator}
2336 \o \l{itemviews/simpletreemodel}{Simple Tree Model}
2337 \o \l{itemviews/chart}{Chart}
2338 \endlist
2339*/
Note: See TracBrowser for help on using the repository browser.