Qt
Internal/Contributor docs for the Qt SDK. <b>Note:</b> These are NOT official API docs; those are found <a href='https://doc.qt.io/'>here</a>.
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. The first approach is
690 covered later in this section.
691
692 \section2 Using an existing delegate
693
694 The standard views provided with Qt use instances of \l QStyledItemDelegate
695 to provide editing facilities. This default implementation of the
696 delegate interface renders items in the usual style for each of the
697 standard views: \l QListView, \l QTableView, and \l QTreeView.
698
699 All the standard roles are handled by the default delegate used by
700 the standard views. The way these are interpreted is described in the
701 QStyledItemDelegate documentation.
702
703 The delegate used by a view is returned by the
704 \l{QAbstractItemView::itemDelegate()}{itemDelegate()} function.
705 The \l{QAbstractItemView::setItemDelegate()}{setItemDelegate()} function
706 allows you to install a custom delegate for a standard view, and it is
707 necessary to use this function when setting the delegate for a custom
708 view.
709
710 \section2 A simple delegate
711
712 The delegate implemented here uses a \l QSpinBox to provide
713 editing facilities, and is mainly intended for use with models
714 that display integers. Although we set up a custom integer-based
715 table model for this purpose, we could easily have used \l
716 QStandardItemModel instead, since the custom delegate controls
717 data entry. We construct a table view to display the contents of
718 the model, and this will use the custom delegate for editing.
719
720 \image spinboxdelegate-example.webp
721
722 We subclass the delegate from \l QStyledItemDelegate because we do not want
723 to write custom display functions. However, we must still provide
724 functions to manage the editor widget:
725
726 \snippet qitemdelegate/spinbox-delegate.cpp declaration
727 \codeline
728 \snippet qitemdelegate/spinbox-delegate.cpp constructor
729
730 Note that no editor widgets are set up when the delegate is
731 constructed. We only construct an editor widget when it is needed.
732
733 \section3 Providing an editor
734
735 In this example, when the table view needs to provide an editor, it
736 asks the delegate to provide an editor widget that is appropriate
737 for the item being modified. The
738 \l{QAbstractItemDelegate::createEditor()}{createEditor()} function is
739 supplied with everything that the delegate needs to be able to set up
740 a suitable widget:
741
742 \snippet qitemdelegate/spinbox-delegate.cpp createEditor
743
744 Note that we do not need to keep a pointer to the editor widget because
745 the view takes responsibility for destroying it when it is no longer
746 needed.
747
748 We install the delegate's default event filter on the editor to ensure
749 that it provides the standard editing shortcuts that users expect.
750 Additional shortcuts can be added to the editor to allow more
751 sophisticated behavior; these are discussed in the section on
752 \l{#EditingHints}{Editing Hints}.
753
754 The view ensures that the editor's data and geometry are set
755 correctly by calling functions that we define later for these purposes.
756 We can create different editors depending on the model index supplied
757 by the view. For example, if we have a column of integers and a column
758 of strings we could return either a \c QSpinBox or a \c QLineEdit,
759 depending on which column is being edited.
760
761 The delegate must provide a function to copy model data into the
762 editor. In this example, we read the data stored in the
763 \l{Qt::ItemDataRole}{display role}, and set the value in the
764 spin box accordingly.
765
766 \snippet qitemdelegate/spinbox-delegate.cpp setEditorData
767
768 In this example, we know that the editor widget is a spin box, but we
769 could have provided different editors for different types of data in
770 the model, in which case we would need to cast the widget to the
771 appropriate type before accessing its member functions.
772
773 \section3 Submitting data to the model
774
775 When the user has finished editing the value in the spin box, the view
776 asks the delegate to store the edited value in the model by calling the
777 \l{QAbstractItemDelegate::setModelData()}{setModelData()} function.
778
779 \snippet qitemdelegate/spinbox-delegate.cpp setModelData
780
781 Since the view manages the editor widgets for the delegate, we only
782 need to update the model with the contents of the editor supplied.
783 In this case, we ensure that the spin box is up-to-date, and update
784 the model with the value it contains using the index specified.
785
786 The standard \l QStyledItemDelegate class informs the view when it has
787 finished editing by emitting the
788 \l{QAbstractItemDelegate::closeEditor()}{closeEditor()} signal.
789 The view ensures that the editor widget is closed and destroyed. In
790 this example, we only provide simple editing facilities, so we never
791 need to emit this signal.
792
793 All the operations on data are performed through the interface
794 provided by \l QAbstractItemModel. This makes the delegate mostly
795 independent from the type of data it manipulates, but some
796 assumptions must be made in order to use certain types of
797 editor widgets. In this example, we have assumed that the model
798 always contains integer values, but we can still use this
799 delegate with different kinds of models because \l{QVariant}
800 provides sensible default values for unexpected data.
801
802 \section3 Updating the editor's geometry
803
804 It is the responsibility of the delegate to manage the editor's
805 geometry. The geometry must be set when the editor is created, and
806 when the item's size or position in the view is changed. Fortunately,
807 the view provides all the necessary geometry information inside a
808 \l{QStyleOptionViewItem}{view option} object.
809
810 \snippet qitemdelegate/spinbox-delegate.cpp updateEditorGeometry
811
812 In this case, we just use the geometry information provided by the
813 view option in the item rectangle. A delegate that renders items with
814 several elements would not use the item rectangle directly. It would
815 position the editor in relation to the other elements in the item.
816
817 \target EditingHints
818 \section3 Editing hints
819
820 After editing, delegates should provide hints to the other components
821 about the result of the editing process, and provide hints that will
822 assist any subsequent editing operations. This is achieved by
823 emitting the \l{QAbstractItemDelegate::closeEditor()}{closeEditor()}
824 signal with a suitable hint. This is taken care of by the default
825 QStyledItemDelegate event filter which we installed on the spin box when
826 it was constructed.
827
828 The behavior of the spin box could be adjusted to make it more user
829 friendly. In the default event filter supplied by QStyledItemDelegate, if
830 the user hits \uicontrol Return to confirm their choice in the spin box,
831 the delegate commits the value to the model and closes the spin box.
832 We can change this behavior by installing our own event filter on the
833 spin box, and provide editing hints that suit our needs; for example,
834 we might emit \l{QAbstractItemDelegate::closeEditor()}{closeEditor()}
835 with the \l{QAbstractItemDelegate::EndEditHint}{EditNextItem} hint to
836 automatically start editing the next item in the view.
837
838 Another approach that does not require the use of an event
839 filter is to provide our own editor widget, perhaps subclassing
840 QSpinBox for convenience. This alternative approach would give us
841 more control over how the editor widget behaves at the cost of
842 writing additional code. It is usually easier to install an event
843 filter in the delegate if you need to customize the behavior of
844 a standard Qt editor widget.
845
846 Delegates do not have to emit these hints, but those that do not will
847 be less integrated into applications, and will be less usable than
848 those that emit hints to support common editing actions.
849
850 \section1 Handling Selections in Item Views
851
852 \section2 Concepts
853
854 The selection model used in the item view classes provides a general
855 description of selections based on the facilities of the model/view
856 architecture. Although the standard classes for manipulating selections are
857 sufficient for the item views provided, the selection model allows you to
858 create specialized selection models to suit the requirements for your own
859 item models and views.
860
861 Information about the items selected in a view is stored in an instance of
862 the \l QItemSelectionModel class. This maintains model indexes for items in
863 a single model, and is independent of any views. Since there can be many
864 views onto a model, it is possible to share selections between views,
865 allowing applications to show multiple views in a consistent way.
866
867 Selections are made up of \e{selection ranges}. These efficiently maintain
868 information about large selections of items by recording only the starting
869 and ending model indexes for each range of selected items. Non-contiguous
870 selections of items are constructed by using more than one selection range
871 to describe the selection.
872
873 Selections are applied to a collection of model indexes held by a selection
874 model. The most recent selection of items applied is known as the
875 \e{current selection}. The effects of this selection can be modified even
876 after its application through the use of certain types of selection
877 commands. These are discussed later in this section.
878
879 \section3 Current item and selected items
880
881 In a view, there is always a current item and a selected item - two
882 independent states. An item can be the current item and selected at the
883 same time. The view is responsible for ensuring that there is always a
884 current item as keyboard navigation, for example, requires a current item.
885
886 The table below highlights the differences between current item and
887 selected items.
888
889 \table 70%
890 \header
891 \li Current Item
892 \li Selected Items
893
894 \row
895 \li There can only be one current item.
896 \li There can be multiple selected items.
897 \row
898 \li The current item will be changed with key navigation or mouse
899 button clicks.
900 \li The selected state of items is set or unset, depending on several
901 pre-defined modes - e.g., single selection, multiple selection,
902 etc. - when the user interacts with the items.
903 \row
904 \li The current item will be edited if the edit key, \uicontrol F2, is
905 pressed or the item is double-clicked (provided that editing is
906 enabled).
907 \li The current item can be used together with an anchor to specify a
908 range that should be selected or deselected (or a combination of
909 the two).
910 \row
911 \li The current item is indicated by the focus rectangle.
912 \li The selected items are indicated with the selection rectangle.
913 \endtable
914
915 When manipulating selections, it is often helpful to think of
916 \l QItemSelectionModel as a record of the selection state of all the items
917 in an item model. Once a selection model is set up, collections of items
918 can be selected, deselected, or their selection states can be toggled
919 without the need to know which items are already selected. The indexes of
920 all selected items can be retrieved at any time, and other components can
921 be informed of changes to the selection model via the signals and slots
922 mechanism.
923
924 \section2 Using a selection model
925
926 The standard view classes provide default selection models that can
927 be used in most applications. A selection model belonging to one view
928 can be obtained using the view's
929 \l{QAbstractItemView::selectionModel()}{selectionModel()} function,
930 and shared between many views with
931 \l{QAbstractItemView::setSelectionModel()}{setSelectionModel()},
932 so the construction of new selection models is generally not required.
933
934 A selection is created by specifying a model, and a pair of model
935 indexes to a \l QItemSelection. This uses the indexes to refer to items
936 in the given model, and interprets them as the top-left and bottom-right
937 items in a block of selected items.
938 To apply the selection to items in a model requires the selection to be
939 submitted to a selection model; this can be achieved in a number of ways,
940 each having a different effect on the selections already present in the
941 selection model.
942
943 \section3 Selecting items
944
945 To demonstrate some of the principal features of selections, we construct
946 an instance of a custom table model with 32 items in total, and open a
947 table view onto its data:
948
949 \snippet itemselection/main.cpp 0
950
951 The table view's default selection model is retrieved for later use.
952 We do not modify any items in the model, but instead select a few
953 items that the view will display at the top-left of the table. To do
954 this, we need to retrieve the model indexes corresponding to the
955 top-left and bottom-right items in the region to be selected:
956
957 \snippet itemselection/main.cpp 1
958
959 To select these items in the model, and see the corresponding change
960 in the table view, we need to construct a selection object then apply
961 it to the selection model:
962
963 \snippet itemselection/main.cpp 2
964
965 The selection is applied to the selection model using a command
966 defined by a combination of
967 \l{QItemSelectionModel::SelectionFlag}{selection flags}.
968 In this case, the flags used cause the items recorded in the
969 selection object to be included in the selection model, regardless
970 of their previous state. The resulting selection is shown by the view.
971
972 \image selected-items1.png
973
974 The selection of items can be modified using various operations that
975 are defined by the selection flags. The selection that results from
976 these operations may have a complex structure, but it is represented
977 efficiently by the selection model. The use of different selection
978 flags to manipulate the selected items is described when we examine
979 how to update a selection.
980
981 \section3 Reading the selection state
982
983 The model indexes stored in the selection model can be read using
984 the \l{QItemSelectionModel::selectedIndexes()}{selectedIndexes()}
985 function. This returns an unsorted list of model indexes that we can
986 iterate over as long as we know which model they are for:
987
988 \snippet reading-selections/window.cpp 0
989
990 The above code uses a range-based for-loop to iterate over,
991 and modify, the items corresponding to the
992 indexes returned by the selection model.
993
994 The selection model emits signals to indicate changes in the
995 selection. These notify other components about changes to both the
996 selection as a whole and the currently focused item in the item
997 model. We can connect the
998 \l{QItemSelectionModel::selectionChanged()}{selectionChanged()}
999 signal to a slot, and examine the items in the model that are selected or
1000 deselected when the selection changes. The slot is called with two
1001 \l{QItemSelection} objects: one contains a list of indexes that
1002 correspond to newly selected items; the other contains indexes that
1003 correspond to newly deselected items.
1004
1005 In the following code, we provide a slot that receives the
1006 \l{QItemSelectionModel::selectionChanged()}{selectionChanged()}
1007 signal, fills in the selected items with
1008 a string, and clears the contents of the deselected items.
1009
1010 \snippet updating-selections/window.cpp 0
1011 \snippet updating-selections/window.cpp 1
1012 \codeline
1013 \snippet updating-selections/window.cpp 2
1014
1015 We can keep track of the currently focused item by connecting the
1016 \l{QItemSelectionModel::currentChanged()}{currentChanged()} signal
1017 to a slot that is called with two model indexes. These correspond to
1018 the previously focused item, and the currently focused item.
1019
1020 In the following code, we provide a slot that receives the
1021 \l{QItemSelectionModel::currentChanged()}{currentChanged()} signal,
1022 and uses the information provided to update the status bar of a
1023 \l QMainWindow:
1024
1025 \snippet updating-selections/window.cpp 3
1026
1027 Monitoring selections made by the user is straightforward with these
1028 signals, but we can also update the selection model directly.
1029
1030 \section3 Updating a selection
1031
1032 Selection commands are provided by a combination of selection flags,
1033 defined by \l{QItemSelectionModel::SelectionFlag}.
1034 Each selection flag tells the selection model how to update its
1035 internal record of selected items when either of the
1036 \l{QItemSelection::select()}{select()} functions are called.
1037 The most commonly used flag is the
1038 \l{QItemSelectionModel::SelectionFlag}{Select} flag
1039 which instructs the selection model to record the specified items as
1040 being selected. The
1041 \l{QItemSelectionModel::SelectionFlag}{Toggle} flag causes the
1042 selection model to invert the state of the specified items,
1043 selecting any deselected items given, and deselecting any currently
1044 selected items. The \l{QItemSelectionModel::SelectionFlag}{Deselect}
1045 flag deselects all the specified items.
1046
1047 Individual items in the selection model are updated by creating a
1048 selection of items, and applying them to the selection model. In the
1049 following code, we apply a second selection of items to the table
1050 model shown above, using the
1051 \l{QItemSelectionModel::SelectionFlag}{Toggle} command to invert the
1052 selection state of the items given.
1053
1054 \snippet itemselection/main.cpp 3
1055
1056 The results of this operation are displayed in the table view,
1057 providing a convenient way of visualizing what we have achieved:
1058
1059 \image selected-items2.png
1060
1061 By default, the selection commands only operate on the individual
1062 items specified by the model indexes. However, the flag used to
1063 describe the selection command can be combined with additional flags
1064 to change entire rows and columns. For example if you call
1065 \l{QItemSelectionModel::select()}{select()} with only one index, but
1066 with a command that is a combination of
1067 \l{QItemSelectionModel::SelectionFlag}{Select} and
1068 \l{QItemSelectionModel::SelectionFlag}{Rows}, the
1069 entire row containing the item referred to is selected.
1070 The following code demonstrates the use of the
1071 \l{QItemSelectionModel::SelectionFlag}{Rows} and
1072 \l{QItemSelectionModel::SelectionFlag}{Columns} flags:
1073
1074 \snippet itemselection/main.cpp 4
1075
1076 Although only four indexes are supplied to the selection model, the
1077 use of the
1078 \l{QItemSelectionModel::SelectionFlag}{Columns} and
1079 \l{QItemSelectionModel::SelectionFlag}{Rows} selection flags means
1080 that two columns and two rows are selected. The following image shows
1081 the result of these two selections:
1082
1083 \image selected-items3.png
1084
1085 The commands performed on the example model have all involved
1086 accumulating a selection of items in the model. It is also possible
1087 to clear the selection, or to replace the current selection with
1088 a new one.
1089
1090 To replace the current selection with a new selection, combine
1091 the other selection flags with the
1092 \l{QItemSelectionModel::SelectionFlag}{Current} flag. A command using
1093 this flag instructs the selection model to replace its current collection
1094 of model indexes with those specified in a call to
1095 \l{QItemSelectionModel::select()}{select()}.
1096 To clear all selections before you start adding new ones,
1097 combine the other selection flags with the
1098 \l{QItemSelectionModel::SelectionFlag}{Clear} flag. This
1099 has the effect of resetting the selection model's collection of model
1100 indexes.
1101
1102 \section3 Selecting all items in a model
1103
1104 To select all items in a model, it is necessary to create a
1105 selection for each level of the model that covers all items in that
1106 level. We do this by retrieving the indexes corresponding to the
1107 top-left and bottom-right items with a given parent index:
1108
1109 \snippet reading-selections/window.cpp 2
1110
1111 A selection is constructed with these indexes and the model. The
1112 corresponding items are then selected in the selection model:
1113
1114 \snippet reading-selections/window.cpp 3
1115
1116 This needs to be performed for all levels in the model.
1117 For top-level items, we would define the parent index in the usual way:
1118
1119 \snippet reading-selections/window.cpp 1
1120
1121 For hierarchical models, the
1122 \l{QAbstractItemModel::hasChildren()}{hasChildren()} function is used to
1123 determine whether any given item is the parent of another level of
1124 items.
1125
1126 \section1 Creating New Models
1127
1128 The separation of functionality between the model/view components allows
1129 models to be created that can take advantage of existing views. This
1130 approach lets us present data from a variety of sources using standard
1131 graphical user interface components, such as QListView, QTableView, and
1132 QTreeView.
1133
1134 The QAbstractItemModel class provides an interface that is flexible
1135 enough to support data sources that arrange information in hierarchical
1136 structures, allowing for the possibility that data will be inserted,
1137 removed, modified, or sorted in some way. It also provides support for
1138 drag and drop operations.
1139
1140 The QAbstractListModel and QAbstractTableModel classes provide support
1141 for interfaces to simpler non-hierarchical data structures, and are
1142 easier to use as a starting point for simple list and table models.
1143
1144 In this section, we create a simple read-only model to explore
1145 the basic principles of the model/view architecture. Later in this
1146 section, we adapt this simple model so that items can be modified
1147 by the user.
1148
1149 For an example of a more complex model, see the
1150 \l{itemviews/simpletreemodel}{Simple Tree Model} example.
1151
1152 The requirements of QAbstractItemModel subclasses is described in more
1153 detail in the \l{Model Subclassing Reference} document.
1154
1155 \section2 Designing a model
1156
1157 When creating a new model for an existing data structure, it is
1158 important to consider which type of model should be used to
1159 provide an interface onto the data. If the data structure can be
1160 represented as a list or table of items, you can subclass
1161 QAbstractListModel or QAbstractTableModel since these classes
1162 provide suitable default implementations for many functions.
1163
1164 However, if the underlying data structure can only be represented
1165 by a hierarchical tree structure, it is necessary to subclass
1166 QAbstractItemModel. This approach is taken in the
1167 \l{itemviews/simpletreemodel}{Simple Tree Model} example.
1168
1169 In this section, we implement a simple model based on a list of
1170 strings, so the QAbstractListModel provides an ideal base class on
1171 which to build.
1172
1173 Whatever form the underlying data structure takes, it is
1174 usually a good idea to supplement the standard QAbstractItemModel API
1175 in specialized models with one that allows more natural access to the
1176 underlying data structure. This makes it easier to populate the model
1177 with data, yet still enables other general model/view components to
1178 interact with it using the standard API. The model described below
1179 provides a custom constructor for just this purpose.
1180
1181 \section2 A read-only example model
1182
1183 The model implemented here is a simple, non-hierarchical, read-only data
1184 model based on the standard QStringListModel class. It has a \l QStringList
1185 as its internal data source, and implements only what is needed to make a
1186 functioning model. To make the implementation easier, we subclass
1187 \l QAbstractListModel because it defines sensible default behavior for list
1188 models, and it exposes a simpler interface than the \l QAbstractItemModel
1189 class.
1190
1191 When implementing a model it is important to remember that
1192 \l QAbstractItemModel does not store any data itself, it merely
1193 presents an interface that the views use to access the data.
1194 For a minimal read-only model it is only necessary to implement a few
1195 functions as there are default implementations for most of the
1196 interface. The class declaration is as follows:
1197
1198 \snippet stringlistmodel/model.h 0
1199 \snippet stringlistmodel/model.h 1
1200 \codeline
1201 \snippet stringlistmodel/model.h 5
1202
1203 Apart from the model's constructor, we only need to implement two
1204 functions: \l{QAbstractItemModel::rowCount()}{rowCount()} returns the
1205 number of rows in the model and \l{QAbstractItemModel::data()}{data()}
1206 returns an item of data corresponding to a specified model index.
1207
1208 Well behaved models also implement
1209 \l{QAbstractItemModel::headerData()}{headerData()} to give tree and
1210 table views something to display in their headers.
1211
1212 Note that this is a non-hierarchical model, so we don't have to worry
1213 about the parent-child relationships. If our model was hierarchical, we
1214 would also have to implement the
1215 \l{QAbstractItemModel::index()}{index()} and
1216 \l{QAbstractItemModel::parent()}{parent()} functions.
1217
1218 The list of strings is stored internally in the \c stringList private
1219 member variable.
1220
1221 \section3 Dimensions of the model
1222
1223 We want the number of rows in the model to be the same as the number of
1224 strings in the string list. We implement the
1225 \l{QAbstractItemModel::rowCount()}{rowCount()} function with this in
1226 mind:
1227
1228 \snippet stringlistmodel/model.cpp 0
1229
1230 Since the model is non-hierarchical, we can safely ignore the model index
1231 corresponding to the parent item. By default, models derived from
1232 QAbstractListModel only contain one column, so we do not need to
1233 reimplement the \l{QAbstractItemModel::columnCount()}{columnCount()}
1234 function.
1235
1236 \section3 Model headers and data
1237
1238 For items in the view, we want to return the strings in the string list.
1239 The \l{QAbstractItemModel::data()}{data()} function is responsible for
1240 returning the item of data that corresponds to the index argument:
1241
1242 \snippet stringlistmodel/model.cpp 1-data-read-only
1243
1244 We only return a valid QVariant if the model index supplied is valid,
1245 the row number is within the range of items in the string list, and the
1246 requested role is one that we support.
1247
1248 Some views, such as QTreeView and QTableView, are able to display headers
1249 along with the item data. If our model is displayed in a view with headers,
1250 we want the headers to show the row and column numbers. We can provide
1251 information about the headers by subclassing the
1252 \l{QAbstractItemModel::headerData()}{headerData()} function:
1253
1254 \snippet stringlistmodel/model.cpp 2
1255
1256 Again, we return a valid QVariant only if the role is one that we support.
1257 The orientation of the header is also taken into account when deciding the
1258 exact data to return.
1259
1260 Not all views display headers with the item data, and those that do may
1261 be configured to hide them. Nonetheless, it is recommended that you
1262 implement the \l{QAbstractItemModel::headerData()}{headerData()} function
1263 to provide relevant information about the data provided by the model.
1264
1265 An item can have several roles, giving out different data depending on the
1266 role specified. The items in our model only have one role,
1267 \l{Qt::ItemDataRole}{DisplayRole}, so we return the data
1268 for items irrespective of the role specified.
1269 However, we could reuse the data we provide for the
1270 \l{Qt::ItemDataRole}{DisplayRole} in
1271 other roles, such as the
1272 \l{Qt::ItemDataRole}{ToolTipRole} that views can use to
1273 display information about items in a tooltip.
1274
1275 \section2 An editable model
1276
1277 The read-only model shows how simple choices could be presented to the
1278 user but, for many applications, an editable list model is much more
1279 useful. We can modify the read-only model to make the items editable
1280 by changing the data() function we implemented for read-only, and
1281 by implementing two extra functions:
1282 \l{QAbstractItemModel::flags()}{flags()} and
1283 \l{QAbstractItemModel::setData()}{setData()}.
1284 The following function declarations are added to the class definition:
1285
1286 \snippet stringlistmodel/model.h 2
1287 \snippet stringlistmodel/model.h 3
1288
1289 \section3 Making the model editable
1290
1291 A delegate checks whether an item is editable before creating an
1292 editor. The model must let the delegate know that its items are
1293 editable. We do this by returning the correct flags for each item in
1294 the model; in this case, we enable all items and make them both
1295 selectable and editable:
1296
1297 \snippet stringlistmodel/model.cpp 3
1298
1299 Note that we do not have to know how the delegate performs the actual
1300 editing process. We only have to provide a way for the delegate to set the
1301 data in the model. This is achieved through the
1302 \l{QAbstractItemModel::setData()}{setData()} function:
1303
1304 \snippet stringlistmodel/model.cpp 4
1305 \snippet stringlistmodel/model.cpp 5
1306
1307 In this model, the item in the string list that corresponds to the
1308 model index is replaced by the value provided. However, before we
1309 can modify the string list, we must make sure that the index is
1310 valid, the item is of the correct type, and that the role is
1311 supported. By convention, we insist that the role is the
1312 \l{Qt::ItemDataRole}{EditRole} since this is the role used by the
1313 standard item delegate. For boolean values, however, you can use
1314 Qt::CheckStateRole and set the Qt::ItemIsUserCheckable flag; a
1315 checkbox is then used for editing the value. The underlying
1316 data in this model is the same for all roles, so this detail just
1317 makes it easier to integrate the model with standard components.
1318
1319 When the data has been set, the model must let the views know that some
1320 data has changed. This is done by emitting the
1321 \l{QAbstractItemModel::dataChanged()}{dataChanged()} signal. Since only
1322 one item of data has changed, the range of items specified in the signal
1323 is limited to just one model index.
1324
1325 Also the data() function needs to be changed to add the Qt::EditRole test:
1326
1327 \snippet stringlistmodel/model.cpp 1
1328
1329 \section3 Inserting and removing rows
1330
1331 It is possible to change the number of rows and columns in a model. In the
1332 string list model it only makes sense to change the number of rows, so we
1333 only reimplement the functions for inserting and removing rows. These are
1334 declared in the class definition:
1335
1336 \snippet stringlistmodel/model.h 4
1337
1338 Since rows in this model correspond to strings in a list, the
1339 \c insertRows() function inserts a number of empty strings into the string
1340 list before the specified position. The number of strings inserted is
1341 equivalent to the number of rows specified.
1342
1343 The parent index is normally used to determine where in the model the
1344 rows should be added. In this case, we only have a single top-level list
1345 of strings, so we just insert empty strings into that list.
1346
1347 \snippet stringlistmodel/model.cpp 6
1348 \snippet stringlistmodel/model.cpp 7
1349
1350 The model first calls the
1351 \l{QAbstractItemModel::beginInsertRows()}{beginInsertRows()} function to
1352 inform other components that the number of rows is about to change. The
1353 function specifies the row numbers of the first and last new rows to be
1354 inserted, and the model index for their parent item. After changing the
1355 string list, it calls
1356 \l{QAbstractItemModel::endInsertRows()}{endInsertRows()} to complete the
1357 operation and inform other components that the dimensions of the model
1358 have changed, returning true to indicate success.
1359
1360 The function to remove rows from the model is also simple to write.
1361 The rows to be removed from the model are specified by the position and
1362 the number of rows given.
1363 We ignore the parent index to simplify our implementation, and just
1364 remove the corresponding items from the string list.
1365
1366 \snippet stringlistmodel/model.cpp 8
1367 \snippet stringlistmodel/model.cpp 9
1368
1369 The \l{QAbstractItemModel::beginRemoveRows()}{beginRemoveRows()} function
1370 is always called before any underlying data is removed, and specifies the
1371 first and last rows to be removed. This allows other components to access
1372 the data before it becomes unavailable.
1373 After the rows have been removed, the model emits
1374 \l{QAbstractItemModel::endRemoveRows()}{endRemoveRows()} to finish the
1375 operation and let other components know that the dimensions of the model
1376 have changed.
1377
1378 \section2 Next steps
1379
1380 We can display the data provided by this model, or any other model, using
1381 the \l QListView class to present the model's items in the form of a vertical
1382 list.
1383 For the string list model, this view also provides a default editor so that
1384 the items can be manipulated. We examine the possibilities made available by
1385 the standard view classes in \l{View Classes}.
1386
1387 The \l{Model Subclassing Reference} document discusses the requirements of
1388 QAbstractItemModel subclasses in more detail, and provides a guide to the
1389 virtual functions that must be implemented to enable various features in
1390 different types of models.
1391
1392 \section1 Item View Convenience Classes
1393
1394 The item-based widgets have names which reflect their uses:
1395 \c QListWidget provides a list of items, \c QTreeWidget displays a
1396 multi-level tree structure, and \c QTableWidget provides a table of cell
1397 items. Each class inherits the behavior of the \c QAbstractItemView
1398 class which implements common behavior for item selection and header
1399 management.
1400
1401 \section2 List widgets
1402
1403 Single level lists of items are typically displayed using a \c QListWidget
1404 and a number of \c{QListWidgetItem}s. A list widget is constructed in the
1405 same way as any other widget:
1406
1407 \snippet qlistwidget-using/mainwindow.cpp 0
1408
1409 List items can be added directly to the list widget when they are
1410 constructed:
1411
1412 \snippet qlistwidget-using/mainwindow.cpp 3
1413
1414 They can also be constructed without a parent list widget and added to
1415 a list at some later time:
1416
1417 \snippet qlistwidget-using/mainwindow.cpp 6
1418 \snippet qlistwidget-using/mainwindow.cpp 7
1419
1420 Each item in a list can display a text label and an icon. The colors
1421 and font used to render the text can be changed to provide a customized
1422 appearance for items. Tooltips, status tips, and "What's
1423 This?" help are all easily configured to ensure that the list is properly
1424 integrated into the application.
1425
1426 \snippet qlistwidget-using/mainwindow.cpp 8
1427
1428 By default, items in a list are presented in the order of their creation.
1429 Lists of items can be sorted according to the criteria given in
1430 \l{Qt::SortOrder} to produce a list of items that is sorted in forward or
1431 reverse alphabetical order:
1432
1433 \snippet qlistwidget-using/mainwindow.cpp 4
1434 \snippet qlistwidget-using/mainwindow.cpp 5
1435
1436 \section2 Tree widgets
1437
1438 Trees or hierarchical lists of items are provided by the \c QTreeWidget
1439 and \c QTreeWidgetItem classes. Each item in the tree widget can have
1440 child items of its own, and can display a number of columns of
1441 information. Tree widgets are created just like any other widget:
1442
1443 \snippet qtreewidget-using/mainwindow.cpp 0
1444
1445 Before items can be added to the tree widget, the number of columns must
1446 be set. For example, we could define two columns, and create a header
1447 to provide labels at the top of each column:
1448
1449 \snippet qtreewidget-using/mainwindow.cpp 1
1450 \snippet qtreewidget-using/mainwindow.cpp 2
1451
1452 The easiest way to set up the labels for each section is to supply a string
1453 list. For more sophisticated headers, you can construct a tree item,
1454 decorate it as you wish, and use that as the tree widget's header.
1455
1456 Top-level items in the tree widget are constructed with the tree widget as
1457 their parent widget. They can be inserted in an arbitrary order, or you
1458 can ensure that they are listed in a particular order by specifying the
1459 previous item when constructing each item:
1460
1461 \snippet qtreewidget-using/mainwindow.cpp 3
1462 \codeline
1463 \snippet qtreewidget-using/mainwindow.cpp 4
1464
1465 Tree widgets deal with top-level items slightly differently to other
1466 items from deeper within the tree. Items can be removed from the top
1467 level of the tree by calling the tree widget's
1468 \l{QTreeWidget::takeTopLevelItem()}{takeTopLevelItem()} function, but
1469 items from lower levels are removed by calling their parent item's
1470 \l{QTreeWidgetItem::takeChild()}{takeChild()} function.
1471 Items are inserted in the top level of the tree with the
1472 \l{QTreeWidget::insertTopLevelItem()}{insertTopLevelItem()} function.
1473 At lower levels in the tree, the parent item's
1474 \l{QTreeWidgetItem::insertChild()}{insertChild()} function is used.
1475
1476 It is easy to move items around between the top level and lower levels
1477 in the tree. We just need to check whether the items are top-level items
1478 or not, and this information is supplied by each item's \c parent()
1479 function. For example, we can remove the current item in the tree widget
1480 regardless of its location:
1481
1482 \snippet qtreewidget-using/mainwindow.cpp 10
1483 \snippet qtreewidget-using/mainwindow.cpp 11
1484
1485 Inserting the item somewhere else in the tree widget follows the same
1486 pattern:
1487
1488 \snippet qtreewidget-using/mainwindow.cpp 8
1489 \snippet qtreewidget-using/mainwindow.cpp 9
1490
1491 \section2 Table widgets
1492
1493 Tables of items similar to those found in spreadsheet applications
1494 are constructed with the \c QTableWidget and \c QTableWidgetItem. These
1495 provide a scrolling table widget with headers and items to use within it.
1496
1497 Tables can be created with a set number of rows and columns, or these
1498 can be added to an unsized table as they are needed.
1499
1500 \snippet qtablewidget-using/mainwindow.h 0
1501 \snippet qtablewidget-using/mainwindow.cpp 0
1502
1503 Items are constructed outside the table before being added to the table
1504 at the required location:
1505
1506 \snippet qtablewidget-using/mainwindow.cpp 3
1507
1508 Horizontal and vertical headers can be added to the table by constructing
1509 items outside the table and using them as headers:
1510
1511 \snippet qtablewidget-using/mainwindow.cpp 1
1512
1513 Note that the rows and columns in the table begin at zero.
1514
1515 \section2 Common features
1516
1517 There are a number of item-based features common to each of the
1518 convenience classes that are available through the same interfaces
1519 in each class. We present these in the following sections with some
1520 examples for different widgets.
1521 Look at the list of \l{Model/View Classes} for each of the widgets
1522 for more details about the use of each function used.
1523
1524 \section3 Hidden items
1525
1526 It is sometimes useful to be able to hide items in an item view widget
1527 rather than remove them. Items for all of the above widgets can be
1528 hidden and later shown again. You can determine whether an item is hidden
1529 by calling the isItemHidden() function, and items can be hidden with
1530 \c setItemHidden().
1531
1532 Since this operation is item-based, the same function is available for
1533 all three convenience classes.
1534
1535 \section3 Selections
1536
1537 The way items are selected is controlled by the widget's selection mode
1538 (\l{QAbstractItemView::SelectionMode}).
1539 This property controls whether the user can select one or many items and,
1540 in many-item selections, whether the selection must be a continuous range
1541 of items. The selection mode works in the same way for all of the
1542 above widgets.
1543
1544 \table 70%
1545 \row
1546 \li \image selection-single.png
1547 \li \b{Single item selections:}
1548 Where the user needs to choose a single item from a widget, the
1549 default \c SingleSelection mode is most suitable. In this mode, the
1550 current item and the selected item are the same.
1551
1552 \row
1553 \li \image selection-multi.png
1554 \li \b{Multi-item selections:}
1555 In this mode, the user can toggle the selection state of any item in the
1556 widget without changing the existing selection, much like the way
1557 non-exclusive checkboxes can be toggled independently.
1558
1559 \row
1560 \li \image selection-extended.png
1561 \li \b{Extended selections:}
1562 Widgets that often require many adjacent items to be selected, such
1563 as those found in spreadsheets, require the \c ExtendedSelection mode.
1564 In this mode, continuous ranges of items in the widget can be selected
1565 with both the mouse and the keyboard.
1566 Complex selections, involving many items that are not adjacent to other
1567 selected items in the widget, can also be created if modifier keys are
1568 used.
1569
1570 If the user selects an item without using a modifier key, the existing
1571 selection is cleared.
1572 \endtable
1573
1574 The selected items in a widget are read using the \c selectedItems()
1575 function, providing a list of relevant items that can be iterated over.
1576 For example, we can find the sum of all the numeric values within a
1577 list of selected items with the following code:
1578
1579 \snippet qtablewidget-using/mainwindow.cpp 4
1580
1581 Note that for the single selection mode, the current item will be in
1582 the selection. In the multi-selection and extended selection modes, the
1583 current item may not lie within the selection, depending on the way the
1584 user formed the selection.
1585
1586 \section3 Searching
1587
1588 It is often useful to be able to find items within an item view widget,
1589 either as a developer or as a service to present to users. All three
1590 item view convenience classes provide a common \c findItems() function
1591 to make this as consistent and simple as possible.
1592
1593 Items are searched for by the text that they contain according to
1594 criteria specified by a selection of values from Qt::MatchFlags.
1595 We can obtain a list of matching items with the \c findItems()
1596 function:
1597
1598 \snippet qtreewidget-using/mainwindow.cpp 7
1599
1600 The above code causes items in a tree widget to be selected if they
1601 contain the text given in the search string. This pattern can also be
1602 used in the list and table widgets.
1603
1604 \section1 Using Drag and Drop with Item Views
1605
1606 Qt's drag and drop infrastructure is fully supported by the model/view framework.
1607 Items in lists, tables, and trees can be dragged within the views, and data can be
1608 imported and exported as MIME-encoded data.
1609
1610 The standard views automatically support internal drag and drop, where items are
1611 moved around to change the order in which they are displayed. By default, drag and
1612 drop is not enabled for these views because they are configured for the simplest,
1613 most common uses. To allow items to be dragged around, certain properties of the
1614 view need to be enabled, and the items themselves must also allow dragging to occur.
1615
1616 The requirements for a model that only allows items to be exported from a
1617 view, and which does not allow data to be dropped into it, are fewer than
1618 those for a fully-enabled drag and drop model.
1619
1620 See also the \l{Model Subclassing Reference} for more information about
1621 enabling drag and drop support in new models.
1622
1623 \section2 Using convenience views
1624
1625 Each of the types of item used with QListWidget, QTableWidget, and QTreeWidget
1626 is configured to use a different set of flags by default. For example, each
1627 QListWidgetItem or QTreeWidgetItem is initially enabled, checkable, selectable,
1628 and can be used as the source of a drag and drop operation; each QTableWidgetItem
1629 can also be edited and used as the target of a drag and drop operation.
1630
1631 Although all of the standard items have one or both flags set for drag and drop,
1632 you generally need to set various properties in the view itself to take advantage
1633 of the built-in support for drag and drop:
1634
1635 \list
1636 \li To enable item dragging, set the view's
1637 \l{QAbstractItemView::dragEnabled}{dragEnabled} property to \c true.
1638 \li To allow the user to drop either internal or external items within the view,
1639 set the view's \l{QAbstractScrollArea::}{viewport()}'s
1640 \l{QWidget::acceptDrops}{acceptDrops} property to \c true.
1641 \li To show the user where the item currently being dragged will be placed if
1642 dropped, set the view's \l{QAbstractItemView::showDropIndicator}{showDropIndicator}
1643 property. This provides the user with continuously updating information about
1644 item placement within the view.
1645 \endlist
1646
1647 For example, we can enable drag and drop in a list widget with the following lines
1648 of code:
1649
1650 \snippet qlistwidget-dnd/mainwindow.cpp 0
1651
1652 The result is a list widget which allows the items to be copied
1653 around within the view, and even lets the user drag items between
1654 views containing the same type of data. In both situations, the
1655 items are copied rather than moved.
1656
1657 To enable the user to move the items around within the view, we
1658 must set the list widget's \l {QAbstractItemView::}{dragDropMode}:
1659
1660 \snippet qlistwidget-dnd/mainwindow.cpp 1
1661
1662 \section2 Using model/view classes
1663
1664 Setting up a view for drag and drop follows the same pattern used with the
1665 convenience views. For example, a QListView can be set up in the same way as a
1666 QListWidget:
1667
1668 \snippet qlistview-dnd/mainwindow.cpp 0
1669
1670 Since access to the data displayed by the view is controlled by a model, the
1671 model used also has to provide support for drag and drop operations. The
1672 actions supported by a model can be specified by reimplementing the
1673 QAbstractItemModel::supportedDropActions() function. For example, copy and
1674 move operations are enabled with the following code:
1675
1676 \snippet qlistview-dnd/model.cpp 10
1677
1678 Although any combination of values from Qt::DropActions can be given, the
1679 model needs to be written to support them. For example, to allow Qt::MoveAction
1680 to be used properly with a list model, the model must provide an implementation
1681 of QAbstractItemModel::removeRows(), either directly or by inheriting the
1682 implementation from its base class.
1683
1684 \section3 Enabling drag and drop for items
1685
1686 Models indicate to views which items can be dragged, and which will accept drops,
1687 by reimplementing the QAbstractItemModel::flags() function to provide suitable
1688 flags.
1689
1690 For example, a model which provides a simple list based on QAbstractListModel
1691 can enable drag and drop for each of the items by ensuring that the flags
1692 returned contain the \l Qt::ItemIsDragEnabled and \l Qt::ItemIsDropEnabled
1693 values:
1694
1695 \snippet qlistview-dnd/model.cpp 7
1696
1697 Note that items can be dropped into the top level of the model, but dragging is
1698 only enabled for valid items.
1699
1700 In the above code, since the model is derived from QStringListModel, we
1701 obtain a default set of flags by calling its implementation of the flags()
1702 function.
1703
1704 \section3 Encoding exported data
1705
1706 When items of data are exported from a model in a drag and drop operation, they
1707 are encoded into an appropriate format corresponding to one or more MIME types.
1708 Models declare the MIME types that they can use to supply items by reimplementing
1709 the QAbstractItemModel::mimeTypes() function, returning a list of standard MIME
1710 types.
1711
1712 For example, a model that only provides plain text would provide the following
1713 implementation:
1714
1715 \snippet qlistview-dnd/model.cpp 9
1716
1717 The model must also provide code to encode data in the advertised format. This
1718 is achieved by reimplementing the QAbstractItemModel::mimeData() function to
1719 provide a QMimeData object, just as in any other drag and drop operation.
1720
1721 The following code shows how each item of data, corresponding to a given list of
1722 indexes, is encoded as plain text and stored in a QMimeData object.
1723
1724 \snippet qlistview-dnd/model.cpp 8
1725
1726 Since a list of model indexes is supplied to the function, this approach is general
1727 enough to be used in both hierarchical and non-heirarchical models.
1728
1729 Note that custom datatypes must be declared as \l{QMetaObject}{meta objects}
1730 and that stream operators must be implemented for them. See the QMetaObject
1731 class description for details.
1732
1733 \section3 Inserting dropped data into a model
1734
1735 The way that any given model handles dropped data depends on both its type
1736 (list, table, or tree) and the way its contents is likely to be presented to
1737 the user. Generally, the approach taken to accommodate dropped data should
1738 be the one that most suits the model's underlying data store.
1739
1740 Different types of model tend to handle dropped data in different ways. List
1741 and table models only provide a flat structure in which items of data are
1742 stored. As a result, they may insert new rows (and columns) when data is
1743 dropped on an existing item in a view, or they may overwrite the item's
1744 contents in the model using some of the data supplied. Tree models are
1745 often able to add child items containing new data to their underlying data
1746 stores, and will therefore behave more predictably as far as the user
1747 is concerned.
1748
1749 Dropped data is handled by a model's reimplementation of
1750 QAbstractItemModel::dropMimeData(). For example, a model that handles a
1751 simple list of strings can provide an implementation that handles data
1752 dropped onto existing items separately to data dropped into the top level
1753 of the model (i.e., onto an invalid item).
1754
1755 Models can forbid dropping on certain items, or depending on the dropped data,
1756 by reimplementing QAbstractItemModel::canDropMimeData().
1757
1758 The model first has to make sure that the operation should be acted on,
1759 the data supplied is in a format that can be used, and that its destination
1760 within the model is valid:
1761
1762 \snippet qlistview-dnd/model.cpp 0
1763 \snippet qlistview-dnd/model.cpp 1
1764
1765 A simple one column string list model can indicate failure if the data
1766 supplied is not plain text, or if the column number given for the drop
1767 is invalid.
1768
1769 The data to be inserted into the model is treated differently depending on
1770 whether it is dropped onto an existing item or not. In this simple example,
1771 we want to allow drops between existing items, before the first item in the
1772 list, and after the last item.
1773
1774 When a drop occurs, the model index corresponding to the parent item will
1775 either be valid, indicating that the drop occurred on an item, or it will
1776 be invalid, indicating that the drop occurred somewhere in the view that
1777 corresponds to top level of the model.
1778
1779 \snippet qlistview-dnd/model.cpp 2
1780
1781 We initially examine the row number supplied to see if we can use it
1782 to insert items into the model, regardless of whether the parent index is
1783 valid or not.
1784
1785 \snippet qlistview-dnd/model.cpp 3
1786
1787 If the parent model index is valid, the drop occurred on an item. In this
1788 simple list model, we find out the row number of the item and use that
1789 value to insert dropped items into the top level of the model.
1790
1791 \snippet qlistview-dnd/model.cpp 4
1792
1793 When a drop occurs elsewhere in the view, and the row number is unusable,
1794 we append items to the top level of the model.
1795
1796 In hierarchical models, when a drop occurs on an item, it would be better to
1797 insert new items into the model as children of that item. In the simple
1798 example shown here, the model only has one level, so this approach is not
1799 appropriate.
1800
1801 \section3 Decoding imported data
1802
1803 Each implementation of \l{QAbstractItemModel::dropMimeData()}{dropMimeData()} must
1804 also decode the data and insert it into the model's underlying data structure.
1805
1806 For a simple string list model, the encoded items can be decoded and streamed
1807 into a QStringList:
1808
1809 \snippet qlistview-dnd/model.cpp 5
1810
1811 The strings can then be inserted into the underlying data store. For consistency,
1812 this can be done through the model's own interface:
1813
1814 \snippet qlistview-dnd/model.cpp 6
1815
1816 Note that the model will typically need to provide implementations of the
1817 QAbstractItemModel::insertRows() and QAbstractItemModel::setData() functions.
1818
1819 \section1 Proxy Models
1820
1821 In the model/view framework, items of data supplied by a single model can be shared
1822 by any number of views, and each of these can possibly represent the same information
1823 in completely different ways.
1824 Custom views and delegates are effective ways to provide radically different
1825 representations of the same data. However, applications often need to provide
1826 conventional views onto processed versions of the same data, such as differently-sorted
1827 views onto a list of items.
1828
1829 Although it seems appropriate to perform sorting and filtering operations as internal
1830 functions of views, this approach does not allow multiple views to share the results
1831 of such potentially costly operations. The alternative approach, involving sorting
1832 within the model itself, leads to the similar problem where each view has to display
1833 items of data that are organized according to the most recent processing operation.
1834
1835 To solve this problem, the model/view framework uses proxy models to manage the
1836 information supplied between individual models and views. Proxy models are components
1837 that behave like ordinary models from the perspective of a view, and access data from
1838 source models on behalf of that view. The signals and slots used by the model/view
1839 framework ensure that each view is updated appropriately no matter how many proxy models
1840 are placed between itself and the source model.
1841
1842 \section2 Using proxy models
1843
1844 Proxy models can be inserted between an existing model and any number of views.
1845 Qt is supplied with a standard proxy model, QSortFilterProxyModel, that is usually
1846 instantiated and used directly, but can also be subclassed to provide custom filtering
1847 and sorting behavior. The QSortFilterProxyModel class can be used in the following way:
1848
1849 \snippet qsortfilterproxymodel/main.cpp 0
1850 \codeline
1851 \snippet qsortfilterproxymodel/main.cpp 1
1852
1853 Since proxy models inherit from QAbstractItemModel, they can be connected to
1854 any kind of view, and can be shared between views. They can also be used to
1855 process the information obtained from other proxy models in a pipeline arrangement.
1856
1857 The QSortFilterProxyModel class is designed to be instantiated and used directly
1858 in applications. More specialized proxy models can be created by subclassing this
1859 classes and implementing the required comparison operations.
1860
1861 \section2 Customizing proxy models
1862
1863 Generally, the type of processing used in a proxy model involves mapping each item of
1864 data from its original location in the source model to either a different location in
1865 the proxy model. In some models, some items may have no corresponding location in the
1866 proxy model; these models are \e filtering proxy models. Views access items using
1867 model indexes provided by the proxy model, and these contain no information about the
1868 source model or the locations of the original items in that model.
1869
1870 QSortFilterProxyModel enables data from a source model to be filtered before
1871 being supplied to views, and also allows the contents of a source model to
1872 be supplied to views as pre-sorted data.
1873
1874 \section3 Custom filtering models
1875
1876 The QSortFilterProxyModel class provides a filtering model that is fairly versatile,
1877 and which can be used in a variety of common situations. For advanced users,
1878 QSortFilterProxyModel can be subclassed, providing a mechanism that enables custom
1879 filters to be implemented.
1880
1881 Subclasses of QSortFilterProxyModel can reimplement two virtual functions that are
1882 called whenever a model index from the proxy model is requested or used:
1883
1884 \list
1885 \li \l{QSortFilterProxyModel::filterAcceptsColumn()}{filterAcceptsColumn()} is used to
1886 filter specific columns from part of the source model.
1887 \li \l{QSortFilterProxyModel::filterAcceptsRow()}{filterAcceptsRow()} is used to filter
1888 specific rows from part of the source model.
1889 \endlist
1890
1891 The default implementations of the above functions in QSortFilterProxyModel
1892 return true to ensure that all items are passed through to views; reimplementations
1893 of these functions should return false to filter out individual rows and columns.
1894
1895 \section3 Custom sorting models
1896
1897 QSortFilterProxyModel instances use std::stable_sort() function to set up
1898 mappings between items in the source model and those in the proxy model, allowing a
1899 sorted hierarchy of items to be exposed to views without modifying the structure of the
1900 source model. To provide custom sorting behavior, reimplement the
1901 \l{QSortFilterProxyModel::lessThan()}{lessThan()} function to perform custom
1902 comparisons.
1903
1904 \section1 Model Subclassing Reference
1905
1906 Model subclasses need to provide implementations of many of the virtual functions
1907 defined in the QAbstractItemModel base class. The number of these functions that need
1908 to be implemented depends on the type of model - whether it supplies views with
1909 a simple list, a table, or a complex hierarchy of items. Models that inherit from
1910 QAbstractListModel and QAbstractTableModel can take advantage of the default
1911 implementations of functions provided by those classes. Models that expose items
1912 of data in tree-like structures must provide implementations for many of the
1913 virtual functions in QAbstractItemModel.
1914
1915 The functions that need to be implemented in a model subclass can be divided into three
1916 groups:
1917
1918 \list
1919 \li \b{Item data handling:} All models need to implement functions to enable views and
1920 delegates to query the dimensions of the model, examine items, and retrieve data.
1921 \li \b{Navigation and index creation:} Hierarchical models need to provide functions
1922 that views can call to navigate the tree-like structures they expose, and obtain
1923 model indexes for items.
1924 \li \b{Drag and drop support and MIME type handling:} Models inherit functions that
1925 control the way that internal and external drag and drop operations are performed.
1926 These functions allow items of data to be described in terms of MIME types that
1927 other components and applications can understand.
1928 \endlist
1929
1930 \section2 Item data handling
1931
1932 Models can provide varying levels of access to the data they provide: They can be
1933 simple read-only components, some models may support resizing operations, and
1934 others may allow items to be edited.
1935
1936 \section2 Read-Only access
1937
1938 To provide read-only access to data provided by a model, the following functions
1939 \e{must} be implemented in the model's subclass:
1940
1941 \table 70%
1942 \row \li \l{QAbstractItemModel::flags()}{flags()}
1943 \li Used by other components to obtain information about each item provided by
1944 the model. In many models, the combination of flags should include
1945 Qt::ItemIsEnabled and Qt::ItemIsSelectable.
1946 \row \li \l{QAbstractItemModel::data()}{data()}
1947 \li Used to supply item data to views and delegates. Generally, models only
1948 need to supply data for Qt::DisplayRole and any application-specific user
1949 roles, but it is also good practice to provide data for Qt::ToolTipRole,
1950 Qt::AccessibleTextRole, and Qt::AccessibleDescriptionRole.
1951 See the Qt::ItemDataRole enum documentation for information about the types
1952 associated with each role.
1953 \row \li \l{QAbstractItemModel::headerData()}{headerData()}
1954 \li Provides views with information to show in their headers. The information is
1955 only retrieved by views that can display header information.
1956 \row \li \l{QAbstractItemModel::rowCount()}{rowCount()}
1957 \li Provides the number of rows of data exposed by the model.
1958 \endtable
1959
1960 These four functions must be implemented in all types of model, including list models
1961 (QAbstractListModel subclasses) and table models (QAbstractTableModel subclasses).
1962
1963 Additionally, the following functions \e{must} be implemented in direct subclasses
1964 of QAbstractTableModel and QAbstractItemModel:
1965
1966 \table 70%
1967 \row \li \l{QAbstractItemModel::columnCount()}{columnCount()}
1968 \li Provides the number of columns of data exposed by the model. List models do not
1969 provide this function because it is already implemented in QAbstractListModel.
1970 \endtable
1971
1972 \section3 Editable items
1973
1974 Editable models allow items of data to be modified, and may also provide
1975 functions to allow rows and columns to be inserted and removed. To enable
1976 editing, the following functions must be implemented correctly:
1977
1978 \table 70%
1979 \row \li \l{QAbstractItemModel::flags()}{flags()}
1980 \li Must return an appropriate combination of flags for each item. In particular,
1981 the value returned by this function must include \l{Qt::ItemIsEditable} in
1982 addition to the values applied to items in a read-only model.
1983 \row \li \l{QAbstractItemModel::setData()}{setData()}
1984 \li Used to modify the item of data associated with a specified model index.
1985 To be able to accept user input, provided by user interface elements, this
1986 function must handle data associated with Qt::EditRole.
1987 The implementation may also accept data associated with many different kinds
1988 of roles specified by Qt::ItemDataRole. After changing the item of data,
1989 models must emit the \l{QAbstractItemModel::dataChanged()}{dataChanged()}
1990 signal to inform other components of the change.
1991 \row \li \l{QAbstractItemModel::setHeaderData()}{setHeaderData()}
1992 \li Used to modify horizontal and vertical header information. After changing
1993 the item of data, models must emit the
1994 \l{QAbstractItemModel::headerDataChanged()}{headerDataChanged()}
1995 signal to inform other components of the change.
1996 \endtable
1997
1998 \section3 Resizable models
1999
2000 All types of model can support the insertion and removal of rows. Table models
2001 and hierarchical models can also support the insertion and removal of columns.
2002 It is important to notify other components about changes to the model's dimensions
2003 both \e before and \e after they occur. As a result, the following functions
2004 can be implemented to allow the model to be resized, but implementations must
2005 ensure that the appropriate functions are called to notify attached views and
2006 delegates:
2007
2008 \table 70%
2009 \row \li \l{QAbstractItemModel::insertRows()}{insertRows()}
2010 \li Used to add new rows and items of data to all types of model.
2011 Implementations must call
2012 \l{QAbstractItemModel::beginInsertRows()}{beginInsertRows()} \e before
2013 inserting new rows into any underlying data structures, and call
2014 \l{QAbstractItemModel::endInsertRows()}{endInsertRows()}
2015 \e{immediately afterwards}.
2016 \row \li \l{QAbstractItemModel::removeRows()}{removeRows()}
2017 \li Used to remove rows and the items of data they contain from all types of model.
2018 Implementations must call
2019 \l{QAbstractItemModel::beginRemoveRows()}{beginRemoveRows()}
2020 \e before rows are removed from any underlying data structures, and call
2021 \l{QAbstractItemModel::endRemoveRows()}{endRemoveRows()}
2022 \e{immediately afterwards}.
2023 \row \li \l{QAbstractItemModel::insertColumns()}{insertColumns()}
2024 \li Used to add new columns and items of data to table models and hierarchical models.
2025 Implementations must call
2026 \l{QAbstractItemModel::beginInsertColumns()}{beginInsertColumns()} \e before
2027 inserting new columns into any underlying data structures, and call
2028 \l{QAbstractItemModel::endInsertColumns()}{endInsertColumns()}
2029 \e{immediately afterwards}.
2030 \row \li \l{QAbstractItemModel::removeColumns()}{removeColumns()}
2031 \li Used to remove columns and the items of data they contain from table models and
2032 hierarchical models.
2033 Implementations must call
2034 \l{QAbstractItemModel::beginRemoveColumns()}{beginRemoveColumns()}
2035 \e before columns are removed from any underlying data structures, and call
2036 \l{QAbstractItemModel::endRemoveColumns()}{endRemoveColumns()}
2037 \e{immediately afterwards}.
2038 \endtable
2039
2040 Generally, these functions should return true if the operation was successful.
2041 However, there may be cases where the operation only partly succeeded; for example,
2042 if less than the specified number of rows could be inserted. In such cases, the
2043 model should return false to indicate failure to enable any attached components to
2044 handle the situation.
2045
2046 The signals emitted by the functions called in implementations of the resizing
2047 API give attached components the chance to take action before any data becomes
2048 unavailable. The encapsulation of insert and remove operations with begin and end
2049 functions also enable the model to manage
2050 \l{QPersistentModelIndex}{persistent model indexes} correctly.
2051
2052 Normally, the begin and end functions are capable of informing other components
2053 about changes to the model's underlying structure. For more complex changes to the
2054 model's structure, perhaps involving internal reorganization, sorting of data or
2055 any other structural change, it is necessary to perform the following sequence:
2056
2057 \list
2058 \li Emit the \l{QAbstractItemModel::layoutAboutToBeChanged()}{layoutAboutToBeChanged()} signal
2059 \li Update internal data which represents the structure of the model.
2060 \li Update persistent indexes using \l{QAbstractItemModel::changePersistentIndexList()}{changePersistentIndexList()}
2061 \li Emit the \l{QAbstractItemModel::layoutChanged()}{layoutChanged()} signal.
2062 \endlist
2063
2064 This sequence can be used for any structural update in lieu of the more
2065 high-level and convenient protected methods. For example, if a model of
2066 two million rows needs to have all odd numbered rows removed, that
2067 is 1 million discountiguous ranges of 1 element each. It would be
2068 possible to use beginRemoveRows and endRemoveRows 1 million times, but
2069 that would obviously be inefficient. Instead, this can be signalled as a
2070 single layout change which updates all necessary persistent indexes at
2071 once.
2072
2073 \section3 Lazy population of model data
2074
2075 Lazy population of model data effectively allows requests for information
2076 about the model to be deferred until it is actually needed by views.
2077
2078 Some models need to obtain data from remote sources, or must perform
2079 time-consuming operations to obtain information about the way the
2080 data is organized. Since views generally request as much information
2081 as possible in order to accurately display model data, it can be useful
2082 to restrict the amount of information returned to them to reduce
2083 unnecessary follow-up requests for data.
2084
2085 In hierarchical models where finding the number of children of a given
2086 item is an expensive operation, it is useful to ensure that the model's
2087 \l{QAbstractItemModel::}{rowCount()} implementation is only called when
2088 necessary. In such cases, the \l{QAbstractItemModel::}{hasChildren()}
2089 function can be reimplemented to provide an inexpensive way for views to
2090 check for the presence of children and, in the case of QTreeView, draw
2091 the appropriate decoration for their parent item.
2092
2093 Whether the reimplementation of \l{QAbstractItemModel::}{hasChildren()}
2094 returns \c true or \c false, it may not be necessary for the view to call
2095 \l{QAbstractItemModel::}{rowCount()} to find out how many children are
2096 present. For example, QTreeView does not need to know how many children
2097 there are if the parent item has not been expanded to show them.
2098
2099 If it is known that many items will have children, reimplementing
2100 \l{QAbstractItemModel::}{hasChildren()} to unconditionally return \c true
2101 is sometimes a useful approach to take. This ensures that each item can
2102 be later examined for children while making initial population of model
2103 data as fast as possible. The only disadvantage is that items without
2104 children may be displayed incorrectly in some views until the user
2105 attempts to view the non-existent child items.
2106
2107 \section2 Navigation and model index creation
2108
2109 Hierarchical models need to provide functions that views can call to navigate the
2110 tree-like structures they expose, and obtain model indexes for items.
2111
2112 \section3 Parents and children
2113
2114 Since the structure exposed to views is determined by the underlying data
2115 structure, it is up to each model subclass to create its own model indexes
2116 by providing implementations of the following functions:
2117
2118 \table 70%
2119 \row \li \l{QAbstractItemModel::index()}{index()}
2120 \li Given a model index for a parent item, this function allows views and delegates
2121 to access children of that item. If no valid child item - corresponding to the
2122 specified row, column, and parent model index, can be found, the function
2123 must return QModelIndex(), which is an invalid model index.
2124 \row \li \l{QAbstractItemModel::parent()}{parent()}
2125 \li Provides a model index corresponding to the parent of any given child item.
2126 If the model index specified corresponds to a top-level item in the model, or if
2127 there is no valid parent item in the model, the function must return
2128 an invalid model index, created with the empty QModelIndex() constructor.
2129 \endtable
2130
2131 Both functions above use the \l{QAbstractItemModel::createIndex()}{createIndex()}
2132 factory function to generate indexes for other components to use. It is normal for
2133 models to supply some unique identifier to this function to ensure that
2134 the model index can be re-associated with its corresponding item later on.
2135
2136 \section2 Drag and drop support and MIME type handling
2137
2138 The model/view classes support drag and drop operations, providing default behavior
2139 that is sufficient for many applications. However, it is also possible to customize
2140 the way items are encoded during drag and drop operations, whether they are copied
2141 or moved by default, and how they are inserted into existing models.
2142
2143 Additionally, the convenience view classes implement specialized behavior that
2144 should closely follow that expected by existing developers.
2145 The \l{#Convenience Views}{Convenience Views} section provides an overview of this
2146 behavior.
2147
2148 \section3 MIME data
2149
2150 By default, the built-in models and views use an internal MIME type
2151 (\c{application/x-qabstractitemmodeldatalist}) to pass around information about
2152 model indexes. This specifies data for a list of items, containing the row and
2153 column numbers of each item, and information about the roles that each item
2154 supports.
2155
2156 Data encoded using this MIME type can be obtained by calling
2157 QAbstractItemModel::mimeData() with a QModelIndexList containing the items to
2158 be serialized.
2159 \omit
2160 The following types are used to store information about
2161 each item as it is streamed into a QByteArray and stored in a QMimeData object:
2162
2163 \table 70%
2164 \header \li Description \li Type
2165 \row \li Row \li int
2166 \row \li Column \li int
2167 \row \li Data for each role \li QMap<int, QVariant>
2168 \endtable
2169
2170 This information can be retrieved for use in non-model classes by calling
2171 QMimeData::data() with the \c{application/x-qabstractitemmodeldatalist} MIME
2172 type and streaming out the items one by one.
2173 \endomit
2174
2175 When implementing drag and drop support in a custom model, it is possible to
2176 export items of data in specialized formats by reimplementing the following
2177 function:
2178
2179 \table 70%
2180 \row \li \l{QAbstractItemModel::mimeData()}{mimeData()}
2181 \li This function can be reimplemented to return data in formats other
2182 than the default \c{application/x-qabstractitemmodeldatalist} internal
2183 MIME type.
2184
2185 Subclasses can obtain the default QMimeData object from the base class
2186 and add data to it in additional formats.
2187 \endtable
2188
2189 For many models, it is useful to provide the contents of items in common format
2190 represented by MIME types such as \c{text/plain} and \c{image/png}. Note that
2191 images, colors and HTML documents can easily be added to a QMimeData object with
2192 the QMimeData::setImageData(), QMimeData::setColorData(), and
2193 QMimeData::setHtml() functions.
2194
2195 \section3 Accepting dropped data
2196
2197 When a drag and drop operation is performed over a view, the underlying model is
2198 queried to determine which types of operation it supports and the MIME types
2199 it can accept. This information is provided by the
2200 QAbstractItemModel::supportedDropActions() and QAbstractItemModel::mimeTypes()
2201 functions. Models that do not override the implementations provided by
2202 QAbstractItemModel support copy operations and the default internal MIME type
2203 for items.
2204
2205 When serialized item data is dropped onto a view, the data is inserted into
2206 the current model using its implementation of QAbstractItemModel::dropMimeData().
2207 The default implementation of this function will never overwrite any data in the
2208 model; instead, it tries to insert the items of data either as siblings of an
2209 item, or as children of that item.
2210
2211 To take advantage of QAbstractItemModel's default implementation for the built-in
2212 MIME type, new models must provide reimplementations of the following functions:
2213
2214 \table 70%
2215 \row \li \l{QAbstractItemModel::insertRows()}{insertRows()}
2216 \li {1, 2} These functions enable the model to automatically insert new data using
2217 the existing implementation provided by QAbstractItemModel::dropMimeData().
2218 \row \li \l{QAbstractItemModel::insertColumns()}{insertColumns()}
2219 \row \li \l{QAbstractItemModel::setData()}{setData()}
2220 \li Allows the new rows and columns to be populated with items.
2221 \row \li \l{QAbstractItemModel::setItemData()}{setItemData()}
2222 \li This function provides more efficient support for populating new items.
2223 \endtable
2224
2225 To accept other forms of data, these functions must be reimplemented:
2226
2227 \table 70%
2228 \row \li \l{QAbstractItemModel::supportedDropActions()}{supportedDropActions()}
2229 \li Used to return a combination of \l{Qt::DropActions}{drop actions},
2230 indicating the types of drag and drop operations that the model accepts.
2231 \row \li \l{QAbstractItemModel::mimeTypes()}{mimeTypes()}
2232 \li Used to return a list of MIME types that can be decoded and handled by
2233 the model. Generally, the MIME types that are supported for input into
2234 the model are the same as those that it can use when encoding data for
2235 use by external components.
2236 \row \li \l{QAbstractItemModel::dropMimeData()}{dropMimeData()}
2237 \li Performs the actual decoding of the data transferred by drag and drop
2238 operations, determines where in the model it will be set, and inserts
2239 new rows and columns where necessary. How this function is implemented
2240 in subclasses depends on the requirements of the data exposed by each
2241 model.
2242 \endtable
2243
2244 If the implementation of the \l{QAbstractItemModel::dropMimeData()}{dropMimeData()}
2245 function changes the dimensions of a model by inserting or removing rows or
2246 columns, or if items of data are modified, care must be taken to ensure that
2247 all relevant signals are emitted. It can be useful to simply call
2248 reimplementations of other functions in the subclass, such as
2249 \l{QAbstractItemModel::setData()}{setData()},
2250 \l{QAbstractItemModel::insertRows()}{insertRows()}, and
2251 \l{QAbstractItemModel::insertColumns()}{insertColumns()}, to ensure that the
2252 model behaves consistently.
2253
2254 In order to ensure drag operations work properly, it is important to
2255 reimplement the following functions that remove data from the model:
2256
2257 \list
2258 \li \l{QAbstractItemModel::}{removeRows()}
2259 \li \l{QAbstractItemModel::}{removeRow()}
2260 \li \l{QAbstractItemModel::}{removeColumns()}
2261 \li \l{QAbstractItemModel::}{removeColumn()}
2262 \endlist
2263
2264 For more information about drag and drop with item views, refer to
2265 \l{Using drag and drop with item views}.
2266
2267 \section3 Convenience views
2268
2269 The convenience views (QListWidget, QTableWidget, and QTreeWidget) override
2270 the default drag and drop functionality to provide less flexible, but more
2271 natural behavior that is appropriate for many applications. For example,
2272 since it is more common to drop data into cells in a QTableWidget, replacing
2273 the existing contents with the data being transferred, the underlying model
2274 will set the data of the target items rather than insert new rows and columns
2275 into the model. For more information on drag and drop in convenience views,
2276 you can see \l{Using drag and drop with item views}.
2277
2278 \section2 Performance optimization for large amounts of data
2279
2280 The \l{QAbstractItemModel::}{canFetchMore()} function checks if the parent
2281 has more data available and returns \c true or false accordingly. The
2282 \l{QAbstractItemModel::}{fetchMore()} function fetches data based on the
2283 parent specified. Both these functions can be combined, for example, in a
2284 database query involving incremental data to populate a QAbstractItemModel.
2285 We reimplement \l{QAbstractItemModel::}{canFetchMore()} to indicate if there
2286 is more data to be fetched and \l{QAbstractItemModel::}{fetchMore()} to
2287 populate the model as required.
2288
2289 Another example would be dynamically populated tree models, where we
2290 reimplement \l{QAbstractItemModel::}{fetchMore()} when a branch in the tree
2291 model is expanded.
2292
2293 If your reimplementation of \l{QAbstractItemModel::}{fetchMore()} adds rows
2294 to the model, you need to call \l{QAbstractItemModel::}{beginInsertRows()}
2295 and \l{QAbstractItemModel::}{endInsertRows()}. Also, both
2296 \l{QAbstractItemModel::}{canFetchMore()} and \l{QAbstractItemModel::}
2297 {fetchMore()} must be reimplemented as their default implementation returns
2298 false and does nothing.
2299
2300 \target Model/View Classes
2301 \section1 The Model/View Classes
2302
2303 These classes use the model/view design pattern in which the
2304 underlying data (in the model) is kept separate from the way the
2305 data is presented and manipulated by the user (in the view).
2306
2307 \annotatedlist model-view
2308
2309 \section1 Related Examples
2310
2311 \list
2312 \li \l{itemviews/simpletreemodel}{Simple Tree Model}
2313 \endlist
2314*/