Qt嵌套向量的自定义树模型
问题描述:
我有一个嵌套的数据结构,我想用QTreeView显示。Qt嵌套向量的自定义树模型
比方说,我有这样的事情:
class Image
{
public:
...
std::vector<Filter> filter_;
};
typedef std::vector<Image> Gallery;
typedef std::vector<Gallery> Galleries;
的QTreeView则应该显示MultiGallery这样的:
Gallery1
|_____Image1
|_____Image2
|_____Image3
Gallery2
|_____Image1
| |_____Filter1
| |_____Filter2
|_____Image2
我读了Qt的模型视图的例子,我知道我必须从QAbstractItemModel派生来创建树模型并实现成员函数:
QVariant data(const QModelIndex &index, int role) const;
QModelIndex index(int row, int column, const QModelIndex &parent=QModelIndex()) const;
QModelIndex parent(const QModelIndex &index) const;
int columnCount(const QModelIndex &parent=QModelIndex()) const;
int rowCount(const QModelIndex &parent=QModelIndex()) const;
我只是不知道最好的方式来实现这些,特别是索引函数。
答
主要想法是有一个索引(即行,列和internalId或internalPointer),您应该能够识别项目及其父项。
您的数据结构不符合此要求。您应该将链接添加到您的对象的父对象,或使用一些辅助结构来存储此信息。
然后,您可以在索引中存储指向您的项目的指针(或指向辅助结构的指针,或更好的辅助结构索引)。