2014-11-14 189 views
0

我派生了QTreeWidget類並創建了我自己的QtPropertyTree。爲了填充小部件(複選框,按鈕等),我使用下面的代碼樹:Qt QTreeWidget替代IndexFromItem?

// in QtPropertyTree.cpp 
QTreeWidgetItem topItem1 = new QTreeWidgetItem(this);  
QTreeWidgetItem subItem = new QTreeWidgetItem(this); 

int column1 = 0 
int Column2 = 1; 

QPushButton myButton = new QPushButton(); 
this->setIndexWidget(this->indexFromItem(this->subItem,column1), myButton); 

QCheckBox myBox = new QCheckBox(); 
this->setIndexWidget(this->indexFromItem(this->subItem,column2), myBox); 

這工作得很好,但問題是,我要避免使用,因爲「indexFromItem」功能它受到保護,並且還有其他類正在填充樹並需要訪問該功能。你知道使用該功能的其他選擇嗎?

回答

4

您可以嘗試使用您的QTreeWidget模型(化QAbstractItemModel)來獲得由列和行號右手食指:

// Row value is 1 because I want to take the index of 
// the second top level item in the tree. 
const int row = 1; 

[..] 

QPushButton myButton = new QPushButton(); 
QModelIndex idx1 = this->model()->index(row, column1); 
this->setIndexWidget(idx1, myButton); 

QCheckBox myBox = new QCheckBox(); 
QModelIndex idx2 = this->model()->index(row, column2); 
this->setIndexWidget(this->indexFromItem(idx2, myBox); 

UPDATE

對於子項,同樣的方法可以用過的。

QModelIndex parentIdx = this->model()->index(row, column1); 
// Get the index of the first child item of the second top level item. 
QModelIndex childIdx = this->model()->index(0, column1, parentIdx); 
+0

感謝。它似乎是這樣工作的。 – Cocomico 2014-11-14 13:50:51

+0

不幸的是它沒有工作。 model() - > index(r,c)只會從頂層項目返回索引,但我需要模型中子項目的索引。 – Cocomico 2014-11-14 14:34:12

+0

@Cocomico,是什麼阻止你使用'index()'函數的子項目呢?只需使用父級的模型索引作爲函數中的第三個參數,如更新後的答案中所示。 – vahancho 2014-11-14 14:46:05

1

顯而易見的解決辦法是去保護indexFromItem這樣的:

class QtPropertyTree { 
    ... 
public: 
    QModelIndex publicIndexFromItem(QTreeWidgetItem * item, int column = 0) const 
    return indexFromItem (item, column) ; 
    } 
} ; 
+0

沒關係。但是,我將不得不在我的其他子類中保留QtPorpertyTree的引用並訪問publicIndexFromItem。同時QtPropertyTree正在訪問子類的方法。有一個交叉引用問題,可以解決。但是這不是一個糟糕的設計實踐? – Cocomico 2014-11-14 15:51:57