Model/View TutorialEvery 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. In the process, we will learn about some basic technologies provided by Qt, such as:
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 examples/tutorials/modelview directory. For more detailed information you may also want to look at the reference documentation If you are completely new to Qt, please read How to Learn Qt if you have not already done so. 1. IntroductionModel/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.
1.1 Standard WidgetsLet'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. 1.2 Model/View to the RescueModel/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. 1.3 Overview of the Model/View WidgetsHere is an overview of the model/view widgets and their corresponding standard widgets.
1.4 Using Adapters between Forms and ModelsHaving 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. 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. Another example of an adapter is QCompleter. Qt has QCompleter for providing auto-completions in Qt widgets such as QComboBox and, as shown below, QLineEdit. QCompleter uses a model as its data source. 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 examples/tutorials/modelview directory. 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) We have the usual main() function: Here is the interesting part: We create an instance of MyModel and use tableView.setModel(&myModel); to pass a pointer of it to to tableView. tableView will invoke the methods of the pointer it has received to find out two things: 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) QAbstractTableModel requires the implementation of three abstract methods. (file source: examples/tutorials/modelview/1_readonly/mymodel.cpp) The number of rows and columns is provided by MyModel::rowCount() and MyModel::columnCount(). When the view has to know what the cell's text is, it calls the method MyModel::data(). Row and column information is specified with parameter index and the role is set to 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, MyModel would have a member called 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. 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: In fact, nothing except for the data() method needs to be changed to set fonts, background colour, alignment and a checkbox. Below is the 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) Each formatting property will be requested from the model with a separate call to the data() method. The role parameter is used to let the model know which property is being requested: sets checkboxes with Qt::Checked Refer to the Qt namespace documentation to learn more about the 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 data() method. In order to track how often the view calls the model, we have put a debug statement in the data() method, which logs onto the error output stream. In our small example, data() will be called 42 times. Each time you hover the cursor over the field, data() will be called again — 7 times for each cell. That's why it is important to make sure that your data is available when data() is invoked and expensive lookup operations are cached. 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) 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) Here is the corresponding slot: (file source: examples/tutorials/modelview/3_changingmodel/mymodel.cpp) We ask the view to read the data in the top left cell again by emitting the dataChanged() signal. Note that we did not explicitly connect the dataChanged() signal to the view. This happened automatically when we called setModel(). Headers can be hidden via a view method: tableView->verticalHeader()->hide(); The header content, however, is set via the model, so we reimplement the headerData() method: (file source: examples/tutorials/modelview/4_headers/mymodel.cpp) Note that method headerData() also has a parameter role which has the same meaning as in MyModel::data(). 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: setData() and flags(). (file source: examples/tutorials/modelview/5_edit/mymodel.h) We use the two-dimensional array QString m_gridData to store our data. This makes m_gridData the core of MyModel. The rest of MyModel acts like a wrapper and adapts m_gridData to the QAbstractItemModel interface. We have also introduced the editCompleted() signal, which makes it possible to transfer the modified text to the window title. (file source: examples/tutorials/modelview/5_edit/mymodel.cpp) setData() will be called each time the user edits a cell. The index parameter tells us which field has been edited and value provides the result of the editing process. The role will always be set to 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 Qt::CheckStateRole. (file source: examples/tutorials/modelview/5_edit/mymodel.cpp) Various properties of a cell can be adjusted with flags(). Returning 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 dataChanged() signal in order for the data that has been changed to be read. 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. 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. This is how our example model looks so far: 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 QStandardItems, which are able to hold all the standard properties of items like text, fonts, checkboxes or brushes. (file source: examples/tutorials/modelview/6_treeview/mainwindow.cpp) We simply instantiate a QStandardItemModel and add a couple of QStandardItems to the constructor. We can then make a hierarchical data structure because a QStandardItem can hold other QStandardItems. Nodes are collapsed and expanded within the view. We want to access a selected item's content in order to output it into the window title together with the hierarchy level. So let's create a couple of items: (file source: examples/tutorials/modelview/7_selections/mainwindow.cpp) Views manage selections within a separate selection model, which can be retrieved with the selectionModel() method. We retrieve the selection Model in order to connect a slot to its selectionChanged() signal. (file source: examples/tutorials/modelview/7_selections/mainwindow.cpp) We get the model index that corresponds to the selection by calling treeView->selectionModel()->currentIndex() and we get the the field's string by using the model index. Then we just calculate the item's hierarchyLevel. Top level items do not have parents and the parent() method will return a default constructed QModelIndex(). This is why we use the 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 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 selectionModel() and assign the result to the second and third view class with setSelectionModel(). 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. 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 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 Star Delegate, in which stars are used to show a rating: The view has a 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. paint() draws stars depending on the content of the underlying data. The data can be looked up by calling index.data(). The delegate's 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: 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 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. Model/View programming is covered quite extensively in the documentation of Qt but also in several good books. More information about these books is available on the 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. Qt 4.7 comes with 17 examples and 2 Demonstrations for model/view. The examples can be found on the Item Views Examples page. Demonstrations are similar to examples except that no walkthrough is provided for the code. Demonstrations are typically more feature rich than examples. A reference document for model/view technology is also available. |