模型/视图组件之间的功能分离允许创建可以利用现有视图的模型。这种方法允许我们使用标准图形用户界面组件(如QListView、QTableView和QTreeView)显示来自各种源的数据。
QAbstractIteModel类提供的接口足够灵活,足以支持在分层结构中排列信息的数据源,从而允许以某种方式插入、删除、修改或排序数据。它还支持拖放操作。
QAbstractListModel和QAbstractTableModel类提供了对更简单的非层次数据结构的接口的支持,并且更容易作为简单列表和表模型的起点使用。
设计模型
为现有数据结构创建新模型时,必须考虑应使用哪种类型的模型为数据提供接口。数据结构是否可以表示为项目的列表或表,可以继承QAbstractListModel或QAbstractTableModel,因为这些类为许多函数提供了合适的默认实现。
如果底层数据结构只能用层次树结构表示,则有必要继承QAbstractItemModel。
可参考简单树模型示例:https://doc.qt.io/qt-6/qtwidgets-itemviews-simpletreemodel-example.html
只读模型示例:
这里实现的模型是一个基于标准QStringListModel类的简单的、无层次的只读数据模型。它有一个QStringList作为它的内部数据源,并且只实现构建一个功能模型所需要的东西。
为了使实现更容易,我们子类化QAbstractListModel,因为它为列表模型定义了合理的默认行为,并且它公开了一个比QAbstractItemModel类更简单的接口。
在实现模型时,重要的是要记住QAbstractItemModel本身并不存储任何数据,它只是提供视图用来访问数据的接口。对于最小只读模型,只需要实现一些函数,因为大多数接口都有默认实现。类声明如下:
#ifndef STRINGLISTMODEL_H
#define STRINGLISTMODEL_H
#include <QAbstractListModel> //列表模型
class StringListModel : public QAbstractListModel{
Q_OBJECT
public:
StringListModel(const QStringList &strings, QObject *parent = nullptr)
: QAbstractListModel(parent), stringList(strings){
}
//返回模型中的行数
int rowCount(const QModelIndex &parent = QModelIndex())const override;
//索引处的数据
QVariant data(const QModelIndex &index,int role) const override;
//给树和表视图一些显示在它们的头文件中的东西
QVariant headerData(int section,Qt::Orientation orientation,int role = Qt::DisplayRole) const override;
private:
QStringList stringList; //数据
};