簡體   English   中英

向Qt樹模型添加一些自定義數據

[英]Adding some custom data to the Qt tree model

我是在Qt中使用模型/視圖范式的菜鳥,並且有以下問題:我有一個樹狀結構,必須通過Qt進行可視化。 我發現QAbstractTableModel非常適合我的需求,因此我編寫了以下代碼:

class columnViewModel : public QAbstractTableModel {
   // some stuff...
};

現在一切正常,但是現在我必須在樹的節點上實現“觀察者”設計模式。 每當節點在TreeView中展開時,都必須向相應的節點添加一個Observer。 每當節點崩潰時,我都必須從節點中刪除此Observer。 所以,我寫點東西,像這樣:

void onExpand( const QModelIndex & Index ... ) {
   Node* myNode = static_cast<Node*>(Index->internalPointer());
   Observer* foo = Observer::create();
   myNode->addObserver(foo);

   // ok up to here, but now where can I save this Observer? I must associate 
   // it with the Node, but I cannot change the Node class. Is there any way 
   // to save it within the index?
}

void onCollapse( const QModelIndex & Index ... ) {
   Node* myNode = static_cast<Node*>Index->internalPointer();
   Observer* foo = // well, what should I write here? Node does not have anything 
                   // like "getObserver()"! Can I extract an Observer from Index?

   myNode->remObserver( foo );
}

我現在沒有代碼片段,因此代碼可能不是有效的Qt,但問題似乎很明顯。 我不能更改Node或Observer類。 我可以有一個內部觀察者列表,但是接下來我必須解決要從特定節點中刪除的觀察者。 有什么方法可以將Observer指針保存在Index中(也許是一些用戶數據),以便在onCollapse中快速解決它? 任何想法都會受到歡迎......

請執行下列操作:

  • 定義一個新角色(類似於Qt :: UserRole),比如說ObserverRole。
  • 使用QAbstractItemModel :: setData將觀察者設置為具有觀察者角色的數據。 代碼草圖:

    this-> model()-> setData(ObserverRole,QVariant :: fromValue(foo));

  • 您可能需要在cpp實現文件中放入元數據聲明,例如

    Q__DECLARE __METATYPE(觀察者*);

以允許QVariant以適當的方式制作變體演員。

  • 您可以使用具有Observer角色的QModelIndex :: data獲取索引的觀察者:

    index.data(ObserverRole);

  • 在模型實現中,添加對觀察者角色返回數據的支持(如果有的話)(就像您可能對Qt :: UserRole或Qt :: DisplayRole所做的那樣)。

更新收到的評論:

通常,QModelIndex :: data為查看器提供數據。 詢問數據時指定的角色允許模型的定制者出於不同的原因提供不同的數據(例如,提供顯示角色的字符串->項目標題)。

如果您不使用此機制獲取數據,則可能不需要QTreeView。 在這種情況下,請使用QTreeWidget,您可以在其中直接使用QTreeWidgetItems並通過setData方法將數據附加到該項目,或者子類QTreeWidgetItem並將數據添加為該子類的成員。

當您要使用模型時,通常使用視圖。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM