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