2012-02-28 76 views
3

我有一個嵌套的數據結構,我想用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; 

我只是不知道最好的方式來實現這些,特別是索引函數。

回答

1

主要想法是有一個索引(即行,列和internalId或internalPointer),您應該能夠識別項目及其父項

您的數據結構不符合此要求。您應該將鏈接添加到您的對象的父對象,或使用一些輔助結構來存儲此信息。

然後,您可以在索引中存儲指向您的項目的指針(或指向輔助結構的指針,或更好的輔助結構索引)。