Qt mvc框架入门 1

文章来自:qt帮助文档 检索model/view programming

Using Models and Views

The following sections explain how to use the model/view pattern in Qt. Each section includes an example and is followed by a section showing how to create new components.

Two models included in Qt

Two of the standard models provided by Qt are QStandardItemModel and QFileSystemModel. QStandardItemModel is a multi-purpose model that can be used to represent various different data structures needed by list, table, and tree views. This model also holds the items of data. QFileSystemModel is a model that maintains information about the contents of a directory. As a result, it does not hold any items of data itself, but simply represents files and directories on the local filing system.

QFileSystemModel provides a ready-to-use model to experiment with, and can be easily configured to use existing data. Using this model, we can show how to set up a model for use with ready-made views, and explore how to manipulate data using model indexes.

#include "mainwindow.h"
#include <QApplication>

#include <QSplitter>
#include <QFileSystemModel>
#include <QTreeView>
#include <QListView>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QSplitter *splitter = new QSplitter;

    QFileSystemModel *model = new QFileSystemModel;
    model->setRootPath(QDir::currentPath());

    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()));

    splitter->setWindowTitle("Two views onto the same file system model");
    splitter->show();

    return a.exec();
}

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. We filter the data supplied by the model by calling the setRootIndex() function on each view, passing a suitable model index from the file system model for the current directory.

猜你喜欢

转载自blog.csdn.net/a1317338022/article/details/81705045