Qt QTreeWidget alternative to IndexFromItem?

Qt QTreeWidget alternative to IndexFromItem?

本文关键字:IndexFromItem to alternative QTreeWidget Qt      更新时间:2023-10-16

我派生了类QTreeWidget并创建了自己的QtPropertyTree。为了用小部件(复选框、按钮等)填充树,我使用以下代码:

// 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"函数,因为它受到保护,并且还有其他类正在填充树并需要访问该功能。您知道使用该函数的任何其他方法吗?

您可以尝试使用 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);

更新

对于子项,可以使用相同的方法。

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

显而易见的解决方案是像这样取消对indexFromItem的保护:

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