1、模型视图结构的理解
Model-View-Controller (MVC) 是由三个对象构成,Model是模型,View是显示,Controller定义了用户界面和用户输入的交互。如果把View和Controller结合起来,就成为了Model/View(模型视图)模式,这种模式仍然是把数据的存储和显示分隔起来的。
模型与数据源通信,为这个架构中的其它组件提供了接口。通信的本质依赖于数据源的类型和Model的实现;
视图从Model获取Model index,它们是数据项的引用。通过提供Model indexes,视图可以从数据源获取数据项;
在标准的视图中,delegate负责渲染数据项。当正在编辑某一项的时候,delegate通过Model index与模型直接通信。
Model,View和Delegate相互之间的通信是通过信号和槽的机制:
从模型发出的信号会通知视图数据源的改变;
从视图发出的信号提供了用户与显示的数据项交互的信息;
从delegate发出的信息用于在编辑时告诉模型和视图编辑的状态。
2、模型视图结构的实战
(1)定义模型框架:
class MyModel: public QAbstractTableModel
{
Q_OBJECT
public:
explicit MyModel(QObject *parent = 0);
virtual int rowCount(const QModelIndex &parent=QModelIndex()) const;// 取得行数
virtual int columnCount(const QModelIndex &parent=QModelIndex()) const;// 取得列数
QVariant data(const QModelIndex &index, int role) const;// 取得数据
QVariant headerData(int section, Qt::Orientation orientation, int role) const;// 取得标题栏数据
}
(2)定义代理框架:
class DataDelegate : public QItemDelegate
{
Q_OBJECT
public:
DataDelegate (QObject *parent = 0);
QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const;
void setEditorData(QWidget *editor, const QModelIndex &index) const;
void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const;
void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const;
};
(3)定义视图框架:
class MyView : public QAbstractItemView
{
Q_OBJECT
public:
MyView (QWidget *parent=0);
QRect visualRect(const QModelIndex &index)const;
void scrollTo(const QModelIndex &index,ScrollHint hint=EnsureVisible);
QModelIndex indexAt(const QPoint &point)const;
//为selections赋初值
void setSelectionModel(QItemSelectionModel *selectionModel);
QRegion itemRegion(QModelIndex index);
void paintEvent(QPaintEvent *);
void mousePressEvent(QMouseEvent *event);
}