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