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