Cocomico
Cocomico

Reputation: 898

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?

Upvotes: 0

Views: 2662

Answers (2)

TonyK
TonyK

Reputation: 17124

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

Upvotes: 2

vahancho
vahancho

Reputation: 21258

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

Upvotes: 4

Related Questions