2014-11-14 188 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