Qt自定义嵌套向量的树模型

Qt custom tree model of nested vector

本文关键字:模型 向量 自定义 嵌套 Qt      更新时间:2023-10-16

我有一个嵌套的数据结构,我想用QTreeView显示。

假设我有这样的东西:

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),您应该能够识别项及其父项

您的数据结构不符合此要求。您应该向对象添加指向父对象的链接,或者使用一些辅助结构来存储这些信息。

然后,您可以将指向项的指针(或指向辅助结构的指针,或结构数组中辅助结构的更好索引)存储在索引中。