简体   繁体   中英

Qt QTreeWidget alternative to IndexFromItem?

I have derived the class QTreeWidget and creating my own QtPropertyTree. In order to populate the tree with widgets (check boxes, buttons, etc) I am using the following code:

// 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);

This works fine, but the problem is that i want to avoid using the "indexFromItem" function since it is protected, and there are other classes that are populating the tree and need access to that funcion. Do you know any alternative to using that function?

You can try to use your QTreeWidget's model (QAbstractItemModel) to get the right index by the column and row numbers:

// 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

For sub items, the same approach can be used.

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);

The obvious solution is to de-protect indexFromItem like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM