Chapter 13.  Models and Views

Table of Contents

13.1. Model-View-Controller (MVC)
13.2. Qt Models and Views
13.2.1. QFileSystemModel
13.2.2. Multiple Views
13.2.3. Delegate Classes
13.3. Table Models
13.3.1. Standard or Abstract?
13.3.2. Editable Models
13.3.3. Sorting and Filtering
13.4. Tree Models
13.4.1. Trolltech Model Testing Tool
13.5. Smarter Pointers
13.6. Exercises: Models and Views
13.7. Review Questions

[ fromfile: modelview.xml id: modelview ]

Abstract

A Model-View design framework provides tools and techniques for separating the set of underlying data classes (the model) from the set of classes that present the user with a GUI (the view). Models typically organize the data, which can be tabular, or hiearchical. In this chapter, we will show how to use the model classes in Qt to represent many different kinds of data.

In several earlier examples, you have seen code that attempts to keep a clean separation between model classes that represent data and view code that presents a user interface. There are several important reasons for enforcing this separation.

First, separating model from view reduces the complexity of each. Model and view code have completely different maintenance imperatives – changes are driven by completely different factors – so it is much easier to maintain both when they are kept separate. Furthermore, the separation of model from view makes it possible to maintain several different, but consistent, views of the same data. The number of sophisticated view classes that can be reused with well-designed models is constantly growing.

Most GUI toolkits offer list, table, and tree view classes, but require the developer to store data inside them. Qt has Widget classes derived from corresponding View classes, as shown in Figure 13.1. For developers who have not used model-view frameworks, these Widget classes may be easier to learn than their View counterparts. Storing data inside these Widgets, however, leads to a strong dependency between the user interface and the underlying structure of the data. This dependency makes it difficult to reuse the Widgets for other types of data or to reuse them in other applications. It also makes it difficult to maintain multiple consistent views of the same data. So, the price for the ease of use and convenience (especially in Qt Designer) is a decrease in flexibility and reusability.

Figure 13.1.  Widgets and Views

Widgets and Views