Using Views with an Existing Model
The QListView and QTreeView classes are the most suitable views to use with QDirModel. The example presented below displays the contents of a directory in a tree view next to the same information in a list view. The views share the user's selection so that the selected items are highlighted in both views.
We set up a QDirModel so that it is ready for use, and create some views to display the contents of a directory. This shows the simplest way to use a model. The construction and use of the model is performed from within a single main() function:
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QSplitter *splitter = new QSplitter;
QDirModel *model = new QDirModel;
The model is set up to use data from a default directory. We create two views so that we can examine the items held in the model in two different ways:
QTreeView *tree = new QTreeView(splitter);
tree->setModel(model);
tree->setRootIndex(model->index(QDir::currentPath()));
QListView *list = new QListView(splitter);
list->setModel(model);
list->setRootIndex(model->index(QDir::currentPath()));
The views are constructed in the same way as other widgets. Setting up a view to display the items in the model is simply a matter of calling its setModel() function with the directory model as the argument. The calls to setRootIndex() tell the views which directory to display by supplying a model index that we obtain from the directory model.
The index() function used in this case is unique to QDirModel; we supply it with a directory and it returns a model index. Model indexes are discussed in the Model Classes chapter.
The rest of the function just displays the views within a splitter widget, and runs the application's event loop:
splitter->setWindowTitle("Two views onto the same directory model");
splitter->show();
return app.exec();
}
In the above example, we neglected to mention how to handle selections of items. This subject is covered in more detail in the chapter on Handling Selections in Item Views. Before examining how selections are handled, you may find it useful to read the Model Classes chapter which describes the concepts used in the model/view framework.
[Previous: An Introduction to Model/View Programming]
[Contents]
[Next: Model Classes]