目的:实现一个树形的树状结构
1. 示例中,其中MineModel的定义:
class MinevModel: public QAbstractItemModel
{
Q_OBJECT
public:
MinevModel();
~MinevModel();
private:
virtual QVariant data(const QModelIndex& index, int role) const;
}
2. 实现一个只包含文本的树状结构
在继承至AbstractItemModel的自定义类中,重写data函数,并且在传入的role为Qt::DisplayRole时,返回对应的string就行。
QVariant
MinevModel::data(const QModelIndex& index, int role) const
{
if (!index.isValid())
return QVariant();
switch (role)
{
case Qt::DisplayRole: // 这里处理了DisplayRole,TreeView的Control端会生成对应的label。
{
return "HelloWorld";
}
default:
break;
}
return QVariant();
}
3. 实现一个子对象是checkbox的树状结构
在继承至AbstractItemModel的自定义类中,重写data函数,并且在传入的role为Qt::DisplayRole时,返回对应的string;在传入的role为Qt:: CheckStateRole时,返回对应的QCheckState;
QVariant
MinevModel::data(const QModelIndex& index, int role) const
{
if (!index.isValid())
return QVariant();
switch (role)
{
case Qt::DisplayRole: // 这里处理了DisplayRole,TreeView的Control端会生成对应的label。
{
return "HelloWorld";
}
case Qt::CheckStateRole: // 这里处理了CheckStateRole,TreeView的Control端会生成对应的checkbox。
{
return Qt::Checked;
}
default:
break;
}
return QVariant();
}
原理
QTreeView采用的时MCV的数据结构,将界面和数据分开处理;只要我们实现model的data函数时,返回对应类型的枚举值(Qt::ItemDataRole),QTreeView会根据返回的枚举值,创建对应的显示(label、checkbox、image等),关于个人对QTreeView的MVC的理解如下图所示,仅代表个人观点,如有问题,请多指教。