source: trunk/doc/src/model-view-programming.qdoc@ 321

Last change on this file since 321 was 2, checked in by Dmitry A. Kuminov, 16 years ago

Initially imported qt-all-opensource-src-4.5.1 from Trolltech.

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