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

Last change on this file since 569 was 561, checked in by Dmitry A. Kuminov, 15 years ago

trunk: Merged in qt 4.6.1 sources.

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