summaryrefslogtreecommitdiffstats
path: root/doc/src/tutorials/modelview.qdoc
blob: ed0825256529ccd9e9376e546f4b3c067e730a0e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the documentation of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:FDL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Free Documentation License
** Alternatively, this file may be used under the terms of the GNU Free
** Documentation License version 1.3 as published by the Free Software
** Foundation and appearing in the file included in the packaging of this
** file.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/

/*!
    \page modelview.html
    \ingroup tutorials
    \startpage {index.html}{Qt Reference Documentation}

    \title Model/View Tutorial
    \brief An introduction to ModelView programming

    Every UI developer should know about ModelView programming and the goal of
    this tutorial is to provide you with an easily understandable introduction
    to this topic.

    Table, list and tree widgets are components frequently used in GUIs. There
    are 2 different ways how these widgets can access their data. The
    traditional way involves widgets which include internal containers for
    storing data. This approach is very intuitive, however, in many non-trivial
    applications, it leads to data synchronization issues.
    The second approach is model/view programming, in
    which widgets do not maintain internal data containers. They access external
    data through a standardized interface and therefore avoid data duplication.
    This may seem complicated at first, but once you take a closer look, it is
    not only easy to grasp, but the many benefits of model/view programming also
    become clearer.

    \image treeview.png

    In the process, we will learn about some basic technologies provided by Qt,
    such as:

    \list
    \o The difference between standard and model/view widgets
    \o Adapters betweeen forms and models
    \o Developing a simple model/view application
    \o Predefined models
    \o Intermediate topics such as:
      \list
      \o Tree views
      \o Selection
      \o Delegates
      \o Debugging with model test
      \endlist
    \endlist

    You will also learn whether your new application can be written easier with
    model/view programming or if classic widgets will work just as well.

    This tutorial includes example code for you to edit and integrate into your
    project. The tutorial's source code is located in Qt's
    \c examples/tutorials/modelview directory.

    For more detailed information you may also want to look at the
    \l{model-view-programming.html}{reference documentation}

    If you are completely new to Qt, please read \l{How to Learn Qt} if you
    have not already done so.


    \section1 1. Introduction

    Model/View is a technology used to separate data from views in widgets that
    handle data sets. Standard widgets are not designed for separating data
    from views and this is why Qt 4 has two different types of widgets. Both
    types of widgets look the same, but they interact with data differently.

    \table
        \row
            \o  Standard widgets use data that is part of the widget.
            \o  \image standardwidget.png
        \row
            \o  View classes operate on external data (the model)
            \o  \image modelview.png
    \endtable

    \section2 1.1 Standard Widgets

    Let's have a closer look at a standard table widget. A table widget is a 2D
    array of the data elements that the user can change. The table widget can be
    integrated into a program flow by reading and writing the data elements that
    the table widget provides. 
    This method is very intuitive and useful in many applications, but displaying 
    and editing a database table with a standard table widget can be problematic.
    Two copies of the data have to be coordinated: one outside the
    widget; one inside the widget. The developer is responsible for
    synchronizing both versions. Besides this, the tight coupling of presentation and data
    makes it harder to write unit tests.

    \section2 1.2 Model/View to the Rescue

    Model/view stepped up to provide a solution that uses a more versatile
    architecture. Model/view eliminates the data consistency problems that may
    occur with standard widgets. Model/view also makes it easier to use more
    than one view of the same data because one model can be passed on to many
    views. The most important difference is that model/view widgets do not store
    data behind the table cells. In fact, they operate directly from your data.
    Since view classes do not know your data's structure, you need to provide a
    wrapper to make your data conform to the QAbstractItemModel interface. A
    view uses this interface to read from and write to your data. Any instance
    of a class that implements QAbstractItemModel is said to be a model. Once
    the view receives a pointer to a model, it will read and display its content
    and be its editor.

    \section2 1.3 Overview of the Model/View Widgets

    Here is an overview of the model/view widgets and their corresponding
    standard widgets.

    \table
        \header
            \o  Widget
            \o  Standard Widget\br
                (an item based convenience class)
            \o  Model/View View Class\br
                (for use with external data)
        \row
            \o  \inlineimage listview.png
            \o  \l QListWidget
            \o  \l QListView
        \row
            \o  \inlineimage tableview.png
            \o  \l QTableWidget
            \o  \l QTableView
        \row
            \o  \inlineimage treeview.png
            \o  \l QTreeWidget
            \o  \l QTreeView
        \row
            \o  \inlineimage columnview.png
            \o
            \o  \l QColumnView shows a tree as a hierarchy of lists
        \row
            \o  \inlineimage modelview-combobox.png
            \o {2, 1} \l QComboBox can work as both a view class and also
                      as a traditional widget
    \endtable

    \section2 1.4 Using Adapters between Forms and Models

    Having adapters between forms and models can come in handy.

    We can edit data stored in tables directly from within the table itself, but
    it's much more comfortable to edit data in text fields. There is no direct
    model/view counterpart that separates data and views for widgets that
    operate on one value (QLineEdit, QCheckBox ...) instead of a dataset, so we
    need an adapter in order to connect the form to the source of data.

    \l QDataWidgetMapper is a great solution because it maps form widgets to a
    table row and makes it very easy to build forms for database tables.

    \image widgetmapper.png

    Another example of an adapter is \l QCompleter. Qt has \l QCompleter for
    providing auto-completions in Qt widgets such as \l QComboBox and, as shown
    below, \l QLineEdit. \l QCompleter uses a model as its data source.

    \image qcompleter.png


    \section1 2. A Simple Model/View Application
    If you want to develop a model/view application, where should you start? 
    We recommend starting with a simple example and extending it step-by-step. 
    This makes understanding the architecture a lot easier. Trying to understand 
    the model/view architecture in detail before invoking the IDE has proven 
    to be less convenient for many developers. It is substantially easier to 
    start with a simple model/view application that has demo data. Give it a 
    try! Simply replace the data in the examples below with your own.

    Below are 7 very simple and independent applications that show different
    sides of model/view programming. The source code can be found inside the
    \c{examples/tutorials/modelview} directory.

    \section2 2.1 A Read Only Table

    We start with an application that uses a QTableView to show data. We will
    add editing capabilities later.

    (file source: examples/tutorials/modelview/1_readonly/main.cpp)
    \snippet examples/tutorials/modelview/1_readonly/main.cpp Quoting ModelView Tutorial

    We have the usual \l {modelview-part2-main-cpp.html}{main()} function:

    Here is the interesting part: We create an instance of MyModel and use 
    \l{QTableView::setModel()}{tableView.setModel(&myModel);} to pass a
    pointer of it to to \l{QTableView}{tableView}. \l{QTableView}{tableView}
    will invoke the methods of the pointer it has received to find out two
    things:

    \list
       \o How many rows and columns should be displayed.
       \o What content should be printed into each cell.
    \endlist

    The model needs some code to respond to this.

    We have a table data set, so let's start with QAbstractTableModel since it
    is easier to use than the more general QAbstractItemModel.

    (file source: examples/tutorials/modelview/1_readonly/mymodel.h)
    \snippet examples/tutorials/modelview/1_readonly/mymodel.h Quoting ModelView Tutorial

    QAbstractTableModel requires the implementation of three abstract methods.

    (file source: examples/tutorials/modelview/1_readonly/mymodel.cpp)
    \snippet examples/tutorials/modelview/1_readonly/mymodel.cpp Quoting ModelView Tutorial

    The number of rows and columns is provided by
    \l{QAbstractItemModel::rowCount()}{MyModel::rowCount()} and
    \l{QAbstractItemModel::columnCount()}{MyModel::columnCount()}. When the view
    has to know what the cell's text is, it calls the method
    \l{QAbstractItemModel::data()}{MyModel::data()}. Row and column information
    is specified with parameter \c index and the role is set to
    \l{Qt::ItemDataRole}{Qt::DisplayRole}. Other roles are covered in the next
    section. In our example, the data that should be displayed is generated. In
    a real application, \c MyModel would have a member called \c MyData, which
    serves as the target for all reading and writing operations.

    This small example demonstrates the passive nature of a model. The model
    does not know when it will be used or which data is needed. It simply
    provides data each time the view requests it.

    What happens when the model's data needs to be changed? How does the view
    realize that data has changed and needs to be read again? The model has to
    emit a signal that indicates what range of cells has changed.  This will be
    demonstrated in section 2.3.

    \section2 2.2 Extending the Read Only Example with Roles

    In addition to controlling what text the view displays, the model also
    controls the text's appearance. When we slightly change the model, we get
    the following result: \image readonlytable_role.png

    In fact, nothing except for the \l{QAbstractItemModel::}{data()} method
    needs to be changed to set fonts, background colour, alignment and a
    checkbox.
    Below is the \l{QAbstractItemModel::data()}{data()} method that produces the
    result shown above. The difference is that this time we use parameter int
    role to return different pieces of information depending on its value.

    (file source: examples/tutorials/modelview/2_formatting/mymodel.cpp)
    \snippet examples/tutorials/modelview/2_formatting/mymodel.cpp Quoting ModelView Tutorial

    Each formatting property will be requested from the model with a separate
    call to the \l{QAbstractItemModel::data()}{data()} method. The \c role
    parameter is used to let the model know which property is being requested:

    \table
        \header
            \o \l{Qt::ItemDataRole}{enum Qt::ItemDataRole}
            \o  Meaning
            \o  Type
        \row
            \o \l{Qt::ItemDataRole}{}Qt::DisplayRole
            \o  text
            \o  QString
        \row
            \o \l{Qt::ItemDataRole}{Qt::FontRole}
            \o  font
            \o  QFont
        \row
            \o \l{Qt::ItemDataRole}{BackgroundRole}
            \o  brush for the background of the cell
            \o  QBrush
        \row
            \o \l{Qt::ItemDataRole}{Qt::TextAlignmentRole}
            \o  text alignment
            \o  \l{Qt::AlignmentFlag}{enum Qt::AlignmentFlag}
        \row
        \o {1, 3}  \l{Qt::ItemDataRole}{Qt::CheckStateRole}
        \o {1, 3} suppresses checkboxes with \l{QVariant}{QVariant()},

              sets checkboxes with \l{Qt::CheckState}{Qt::Checked}

              or \l{Qt::CheckState}{Qt::Unchecked}
        \o {1, 3}  \l{Qt::ItemDataRole}{enum Qt::ItemDataRole}
    \endtable

    Refer to the Qt namespace documentation to learn more about the
    \l{Qt::ItemDataRole}{Qt::ItemDataRole} enum's capabilities.

    Now we need to determine how using a separated model impacts the
    application's performance, so let's trace how often the view calls the
    \l{QAbstractItemModel::}{data()} method. In order to track how often the
    view calls the model, we have put a debug statement in the
    \l{QAbstractItemModel::}{data()} method, which logs onto the error output
    stream. In our small example, \l{QAbstractItemModel::}{data()} will be
    called 42 times.
    Each time you hover the cursor over the field,
    \l{QAbstractItemModel::}{data()} will be called again \mdash 7 times for
    each cell. That's why it is important to make sure that your data is
    available when \l{QAbstractItemModel::}{data()} is invoked and expensive
    lookup operations are cached.

    \section2 2.3 A Clock inside a Table Cell

    \image clock.png

    We still have a read only table, but this time the content changes every
    second because we are showing the current time.

    (file source: examples/tutorials/modelview/3_changingmodel/mymodel.cpp)
    \snippet examples/tutorials/modelview/3_changingmodel/mymodel.cpp quoting mymodel_QVariant

    Something is missing to make the clock tick. We need to tell the view every
    second that the time has changed and that it needs to be read again. We do
    this with a timer. In the constructor, we set its interval to 1 second and
    connect its timeout signal.

    (file source: examples/tutorials/modelview/3_changingmodel/mymodel.cpp)
    \snippet examples/tutorials/modelview/3_changingmodel/mymodel.cpp quoting mymodel_a

    Here is the corresponding slot:

    (file source: examples/tutorials/modelview/3_changingmodel/mymodel.cpp)
    \snippet examples/tutorials/modelview/3_changingmodel/mymodel.cpp quoting mymodel_b

    We ask the view to read the data in the top left cell again by emitting the
    \l{QAbstractItemModel::}{dataChanged()} signal.  Note that we did not
    explicitly connect the \l{QAbstractItemModel::}{dataChanged()} signal to the
    view. This happened automatically when we called \l{QTableView::}{setModel()}.

    \section2 2.4 Setting up Headers for Columns and Rows

    Headers can be hidden via a view method: \c{tableView->verticalHeader()->hide();}
    \image modelview-header.png

    The header content, however, is set via the model, so we reimplement the
    \l{QAbstractItemModel::headerData()}{headerData()} method:

    (file source: examples/tutorials/modelview/4_headers/mymodel.cpp)
    \snippet examples/tutorials/modelview/4_headers/mymodel.cpp quoting mymodel_c

    Note that method \l{QAbstractItemModel::headerData()}{headerData()} also has
    a parameter role which has the same meaning as in
    \l{QAbstractItemModel::data()}{MyModel::data()}.

    \section2 2.5 The Minimal Editing Example

    In this example, we are going to build an application that automatically
    populates a window title with content by repeating values entered into table
    cells. To be able to access the window title easily we put the QTableView in
    a QMainWindow.

    The model decides whether editing capabilities are available. We only have
    to modify the model in order for the available editing capabilities to be
    enabled. This is done by reimplementing the following virtual methods:
    \l{QAbstractItemModel::}{setData()} and \l{QAbstractItemModel::}{flags()}.

    (file source: examples/tutorials/modelview/5_edit/mymodel.h)
    \snippet examples/tutorials/modelview/5_edit/mymodel.h Quoting ModelView Tutorial

    We use \c the two-dimensional array QString \c m_gridData to store our data.
    This makes \c m_gridData the core of \c MyModel.  The rest of \c MyModel acts
    like a wrapper and adapts \c m_gridData to the QAbstractItemModel
    interface. We have also introduced the \c editCompleted() signal, which
    makes it possible to transfer the modified text to the window title.

    (file source: examples/tutorials/modelview/5_edit/mymodel.cpp)
    \snippet examples/tutorials/modelview/5_edit/mymodel.cpp quoting mymodel_e

    \l{QAbstractItemModel::setData()}{setData()} will be called each time the
    user edits a cell. The \c index parameter tells us which field has been
    edited and \c value  provides the result of the editing process. The role
    will always be set to \l Qt::EditRole because our cells only contain text.
    If a checkbox were present and user permissions are set to allow the
    checkbox to be selected, calls would also be made with the role set to
    \l Qt::CheckStateRole.

    (file source: examples/tutorials/modelview/5_edit/mymodel.cpp)
    \snippet examples/tutorials/modelview/5_edit/mymodel.cpp quoting mymodel_f

    Various properties of a cell can be adjusted with
    \l{QAbstractItemModel::flags()}{flags()}.

    Returning \l{Qt::ItemFlag}{Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsEnabled}
    is enough to show an editor that a cell can be selected.

    If editing one cell modifies more data than the data in that particular
    cell, the model must emit a \l{QAbstractItemModel::}{dataChanged()} signal
    in order for the data that has been changed to be read.


    \section1 3. Intermediate Topics

    \section2 3.1 TreeView

    You can convert the example above into an application with a tree view.
    Simply replace QTableView with QTreeView, which results in a read/write
    tree. No changes have to be made to the model. The tree won't have any
    hierarchies because there aren't any hierarchies in the model itself.

    \image dummy_tree.png

    QListView, QTableView and QTreeView all use a model abstraction, which is a
    merged list, table and tree. This makes it possible to use several different
    types of view classes from the same model.

    \image list_table_tree.png

    This is how our example model looks so far:

    \image example_model.png

    We want to present a real tree. We have wrapped our data in the examples
    above in order to make a model. This time we use QStandardItemModel, which
    is a container for hierarchical data that also implements
    QAbstractItemModel. To show a tree, QStandardItemModel must be populated
    with \l{QStandardItem}s, which are able to hold all the standard properties
    of items like text, fonts, checkboxes or brushes.

    \image tree_2_with_algorithm.png

    (file source: examples/tutorials/modelview/6_treeview/mainwindow.cpp)
    \snippet examples/tutorials/modelview/6_treeview/mainwindow.cpp Quoting ModelView Tutorial

    We simply instantiate a QStandardItemModel and add a couple of
    \l{QStandardItem}{QStandardItems} to the constructor. We can then make a
    hierarchical data structure because a QStandardItem can hold other
    \l{QStandardItem}{QStandardItems}. Nodes are collapsed and expanded within
    the view.

    \section2 3.2 Working with Selections

    We want to access a selected item's content in order to output it into the
    window title together with the hierarchy level.

    \image selection2.png

    So let's create a couple of items:

    (file source: examples/tutorials/modelview/7_selections/mainwindow.cpp)
    \snippet examples/tutorials/modelview/7_selections/mainwindow.cpp quoting modelview_a

    Views manage selections within a separate selection model, which can be
    retrieved with the \l{QAbstractItemView::}{selectionModel()} method. We
    retrieve the selection Model in order to connect a slot to its
    \l{QAbstractItemView::}{selectionChanged()} signal.

    (file source: examples/tutorials/modelview/7_selections/mainwindow.cpp)
    \snippet examples/tutorials/modelview/7_selections/mainwindow.cpp quoting modelview_b

    We get the model index that corresponds to the selection by calling
    \l{QItemSelectionModel::currentIndex()}{treeView->selectionModel()->currentIndex()}
    and we get the the field's string by using the model index. Then we just
    calculate the item's \c hierarchyLevel.  Top level items do not have parents
    and the \l{QAbstractItemModel::}{parent()} method will return a default
    constructed \l{QModelIndex}{QModelIndex()}. This is why we use the
    \l{QAbstractItemModel::}{parent()} method to iterate to the top level while
    counting the steps performed during iteration.

    The selection model (as shown above) can be retrieved, but it can also be
    set with \l{QAbstractItemView}{QAbstractItemView::setSelectionModel}. This
    is how it's possible to have 3 view classes with synchronised selections
    because only one instance of a selection model is used. To share a selection
    model between 3 views use \l{QAbstractItemView::}{selectionModel()} and
    assign the result to the second and third view class with
    \l{QAbstractItemView::}{setSelectionModel()}.

    \section2 3.3 Predefined Models

    The typical way to use model/view is to wrap specific data to make it usable
    with view classes. Qt, however, also provides predefined models for common
    underlying data structures. If one of the available data structures is
    suitable for your application, a predefined model can be a good choice.

    \table
        \row
            \o  QStringListModel
            \o  Stores a list of strings
        \row
            \o  QStandardItemModel
            \o  Stores arbitrary hierarchical items
        \row
            \o  QFileSystemModel\br
                QDirModel
            \o  Encapsulate the local file system
        \row
            \o  QSqlQueryModel
            \o  Encapsulate an SQL result set
        \row
            \o  QSqlTableModel
            \o  Encapsulates an SQL table
        \row
            \o  QSqlRelationalTableModel
            \o  Encapsulates an SQL table with foreign keys
        \row
            \o  QSortFilterProxyModel
            \o  Sorts and/or filters another model

    \endtable

    \section2 3.4 Delegates

    In all examples so far, data is presented as text or a checkbox in a cell
    and is edited as text or a checkbox. The component that provides these
    presentation and editing services is called a \e delegate. We are only just
    beginning to work with the delegate because the view uses a default
    delegate. But imagine that we want to have a different editor (e.g., a
    slider or a drop down list) Or imagine that we want to present data as
    graphics.
    Let's take a look at an example called \l{Star Delegate Example}{Star
    Delegate}, in which stars are used to show a rating:

    \image stardelegate.png

    The view has a \l{QAbstractItemView::}{setItemDelegate()} method that
    replaces the default delegate and installs a custom delegate.
    A new delegate can be written by creating a class that inherits from
    QStyledItemDelegate. In order to write a delegate that displays stars and
    has no input capabilities, we only need to override 2 methods.

    \code
     class StarDelegate : public QStyledItemDelegate
     {
         Q_OBJECT
     public:
         StarDelegate(QWidget *parent = 0);
         void paint(QPainter *painter, const QStyleOptionViewItem &option,
                    const QModelIndex &index) const;
         QSize sizeHint(const QStyleOptionViewItem &option,
                        const QModelIndex &index) const;
     };
    \endcode

    \l{QStyledItemDelegate::}{paint()} draws stars depending on the content of
    the underlying data.  The data can be looked up by calling
    \l{QModelIndex::data()}{index.data()}. The delegate's
    \l{QAbstractItemDelegate::}{sizeHint()} method is used to obtain each
    star's dimensions, so the the cell will provide enough height and width to
    accommodate the stars.

    Writing custom delegates is the right choice if you want to show your data
    with a custom graphical representation inside the grid of the view class. If
    you want to leave the grid, you would not use a custom delegate but a custom
    view class.

    Other references to delegates in Qt Documentation:

    \list
    \o \l{Spin Box Delegate Example}
    \o \l{QAbstractItemDelegate}{QAbstractItemDelegate Class Reference}
    \o \l{QSqlRelationalDelegate}{QSqlRelationalDelegate Class Reference}
    \o \l{QStyledItemDelegate}{QStyledItemDelegate Class Reference}
    \o \l{QItemDelegate}{QItemDelegate Class Reference}
    \endlist


    \section2 3.5 Debugging with ModelTest

    The passive nature of models provides new challenges for programmers.
    Inconsistencies in the model can cause the application to crash. Since the
    model is hit by numerous calls from the view, it is hard to find out which
    call has crashed the application and which operation has introduced the
    problem.

    Qt Labs provides software called
    \l{http://labs.qt.nokia.com/page/Projects/Itemview/Modeltest}{ModelTest},
    which checks models while your programming is running. Every time the model
    is changed, ModelTest scans the model and reports errors with an assert.
    This is especially important for tree models, since their hierarchical
    nature leaves many possibilities for subtle inconsistencies.

    Unlike view classes, ModelTest uses out of range indexes to test the model.
    This means your application may crash with ModelTest even if it runs
    perfectly without it. So you also need to handle all of the indexes that are
    out of range when using ModelTest.


    \section1 4. Good Sources of Additional Information

    \section2 4.1 Books

    Model/View programming is covered quite extensively in the documentation of
    Qt but also in several good books.

    \list 1
       \o \bold{C++ GUI Programming with Qt 4} / Jasmin Blanchette, Mark Summerfield,
          \e{Prentice Hall, 2nd edition}, ISBN 0-13-235416-0. Also available in
          German: \bold{C++ GUI Programmierung mit Qt 4: Die offizielle Einführung},
          \e{Addison-Wesley}, ISBN 3-827327-29-6
       \o \bold{The Book of Qt4, The Art of Building Qt Applications} / Daniel Molkentin,
          \e{Open Source Press}, ISBN 1-59327-147-6.
          Translated from \bold{Qt 4, Einführung in die Applikationsentwicklung},
          \e{Open Source Press}, ISBN 3-937514-12-0.
       \o \bold{Foundations of Qt Development} / Johan Thelin, \e{Apress}, ISBN 1-59059-831-8.
       \o \bold{Advanced Qt Programming} / Mark Summerfield, \e{Prentice Hall}, ISBN 0-321-63590-6. 
          This book covers Model/View programming on more than 150 pages. 
    \endlist

    More information about these books is available on the
    \l{Books about Qt Programming}{Qt Web site}.

    The following list provides an overview of example programs contained in the first three
    books listed above. Some of them make very good templates for developing similar
    applications.

    \table
        \header
            \o  Example name
            \o  View class used
            \o  Model used
            \o  Aspects covered
            \o
        \row
            \o  Team Leaders
            \o  QListview
            \o  QStringListModel
            \o
            \o  Book 1, Chapter 10, Figure 10.6
        \row
            \o  Directory Viewer
            \o  QTreeView
            \o  QDirModel
            \o
            \o  Book 1, Chapter 10, Figure 10.7
        \row
            \o  Color Names
            \o  QListView
            \o  QSortFilterProxyModel
                applied to QStringListModel
            \o
            \o  Book 1, Chapter 10, Figure 10.8
        \row
            \o  Currencies
            \o  QTableView
            \o  custom model based on
                QAbstractTableModel
            \o  Read only
            \o  Book 1, Chapter 10, Figure 10.10
        \row
            \o  Cities
            \o  QTableView
            \o  Custom model based on
                QAbstractTableModel
            \o  Read / write
            \o  Book 1, Chapter 10, Figure 10.12
        \row
            \o  Boolean Parser
            \o  QTreeView
            \o  Custom model based on
                QAbstractItemModel
            \o  Read only
            \o  Book 1, Chapter 10, Figure 10.14
        \row
            \o  Track Editor
            \o  {2, 1} QTableWidget
            \o  Custom delegate providing a custom editor
            \o  Book 1, Chapter 10, Figure 10.15

        \row
            \o  Four directory views
            \o  QListView
                QTableView
                QTreeView
            \o  QDirModel
            \o  Demonstrates the use of multiple views
            \o  Book2, Chapter 8.2
        \row
            \o  Address Book
            \o  QListView
                QTableView
                QTreeView
            \o  Custom model based on
                QAbstractTableModel
            \o  Read / write
            \o  Book2, Chapter 8.4
        \row
            \o  Address Book with sorting
            \o
            \o  QProxyModel
            \o  Introducing sort and filter capabilities
            \o  Book2, Chapter 8.5
        \row
            \o  Address Book
                with checkboxes
            \o
            \o
            \o  Introducing checkboxes in model/view
            \o  Book2, Chapter 8.6
        \row
            \o  Address Book with transposed grid
            \o
            \o  Custom proxy Model based on QAbstractProxyModel
            \o  Introducing a custom model
            \o  Book2, Chapter 8.7
        \row
            \o  Address Book with drag and drop
            \o
            \o
            \o  Introducing drag and drop support
            \o  Book2, Chapter 8.8
        \row
            \o  Address Book with custom editor
            \o
            \o
            \o  Introducing custom delegates
            \o  Book2, Chapter 8.9
        \row
            \o  Views
            \o  QListView
                QTableView
                QTreeView
            \o  QStandardItemModel
            \o  Read only
            \o  Book 3, Chapter 5, figure 5-3
        \row
            \o  Bardelegate
            \o  QTableView
            \o
            \o  Custom delegate for presentation based on QAbstractItemDelegate
            \o  Book 3, Chapter 5, figure 5-5
        \row
            \o  Editdelegate
            \o  QTableView
            \o
            \o  Custom delegate for editing based on QAbstractItemDelegate
            \o  Book 3, Chapter 5, figure 5-6
        \row
            \o  Singleitemview
            \o  Custom view based on QAbstractItemView
            \o
            \o  Custom view
            \o  Book 3,
                Chapter 5,
                figure 5-7
        \row
            \o  listmodel
            \o  QTableView
            \o  Custom Model based on QAbstractTableModel
            \o  Read only
            \o  Book 3, Chapter 5, Figure 5-8
        \row
            \o  treemodel
            \o  QTreeView
            \o  Custom Model based on QAbstractItemModel
            \o  Read only
            \o  Book 3, Chapter 5, Figure 5-10
        \row
            \o  edit integers
            \o  QListView
            \o  Custom Model based on QAbstractListModel
            \o  Read / write
            \o  Book 3, Chapter 5, Listing 5-37, Figure 5-11
        \row
            \o  sorting
            \o  QTableView
            \o  QSortFilterProxyModel applied to QStringListModel
            \o  Demonstrates sorting
            \o  Book 3, Chapter 5, Figure 5-12
    \endtable


    \section2 4.2 Qt Documentation

    Qt 4.7 comes with 17 examples and 2 Demonstrations for model/view.
    The examples can be found on the \l{Item Views Examples} page.

    \table
        \header
            \o  Example name
            \o  View class used
            \o  Model used
            \o  Aspects covered
        \row
            \o  Address Book
            \o  QTableView
            \o  QAbstractTableModel
                QSortFilterProxyModel
            \o  Usage of QSortFilterProxyModel to generate different
                subsets from one data pool
        \row
            \o  Basic Sort/Filter Model
            \o  QTreeView
            \o  QStandardItemModel
                QSortFilterProxyModel
            \o
        \row
            \o  Chart
            \o  Custom view
            \o  QStandardItemModel
            \o  Designing custom views that cooperate with selection models
        \row
            \o  Color Editor Factory
            \o  {2, 1}  QTableWidget
            \o  Enhancing the standard delegate with a new custom editor to choose colours
        \row
            \o  Combo Widget Mapper
            \o  QDataWidgetMapper to map QLineEdit, QTextEdit and QComboBox
            \o  QStandardItemModel
            \o  Shows how a QComboBox can serve as a view class
        \row
            \o  Custom Sort/Filter Model
            \o  QTreeView
            \o  QStandardItemModel
                QSortFilterProxyModel
            \o  Subclass QSortFilterProxyModel for advanced sorting and filtering
        \row
            \o  Dir View
            \o  QTreeView
            \o  QDirModel
            \o  Very small example to demonstrate how to assign a model to a view
        \row
            \o  Editable Tree Model
            \o  QTreeView
            \o  Custom tree model
            \o  Comprehensive example for working with trees, demonstrates
                editing cells and tree structure with an underlying custom
                model
        \row
            \o  Fetch More
            \o  QListView
            \o  Custom list model
            \o  Dynamically changing model
        \row
            \o  Frozen Column
            \o  QTableView
            \o  QStandardItemModel
            \o
        \row
            \o  Pixelator
            \o  QTableView
            \o  Custom table model
            \o  Implementation of a custom delegate
        \row
            \o  Puzzle
            \o  QListView
            \o  Custom list model
            \o  Model/view with drag and drop
        \row
            \o  Simple DOM Model
            \o  QTreeView
            \o  Custom tree model
            \o  Read only example for a custom tree model
        \row
            \o  Simple Tree Model
            \o  QTreeView
            \o  Custom tree model
            \o  Read only example for a custom tree model
        \row
            \o  Simple Widget Mapper
            \o  QDataWidgetMapper to map QLineEdit, QTextEdit and QSpinBox
            \o  QStandardItemModel
            \o  Basic QDataWidgetMapper usage
        \row
            \o  Spin Box Delegate
            \o  QTableView
            \o  QStandardItemModel
            \o  Custom delegate that uses a spin box as a cell editor
        \row
            \o  Star Delegate
            \o  {2, 1}  QTableWidget
            \o  Comprehensive custom delegate example.
    \endtable

    \l{Qt Demonstrations}{Demonstrations} are similar to examples except that no
    walkthrough is provided for the code. Demonstrations are typically more
    feature rich than examples.

    \list
       \o   The \bold Interview demonstration shows the same model and
            selection being shared between three different views.
       \o   The \bold Spreadsheet demonstration illustrates the use of a
            table view as a spreadsheet, using custom delegates to render
            each item according to the type of data it contains.
    \endlist

    A \l{Model/View Programming}{reference document} for model/view technology
    is also available.
*/

/*!
    \page modelview-part2-main-cpp.html
    \title main.cpp
    \quotefile tutorials/modelview/1_readonly/main.cpp
*/