【问题标题】:Qt QTreeWidget alternative to IndexFromItem?Qt QTreeWidget 替代 IndexFromItem?
【发布时间】:2014-11-14 12:59:22
【问题描述】:

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

【问题讨论】:

    标签: c++ qt qtreewidget


    【解决方案1】:

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

    【讨论】:

    • 不幸的是它没有工作。 model()->index(r,c) 只返回顶级项目的索引,但我需要模型中子项目的索引。
    • @Cocomico,是什么阻止了您对子项目也使用index() 功能?只需使用父模型索引作为函数中的第三个参数,如更新的答案所示。
    • 是不是意味着如果我有嵌套几个级别的子项,我必须总是调用 model()->index() 并将父索引作为第三个参数?假设我有 3 个级别,所以它看起来像:QModelIndex i1 = model()->index(a,b)QModelIndex i2 = model()->index(c,d, i1)QModelIndex i3 = model()->index(e,f, i2)
    • 或者你能想到更简单的方法吗?
    • 很好的答案。最后一件事。我仍然会从另一个外部类调用函数 setIndexWidget(),这意味着该类需要对 QTreeWidget 类的引用,这是不是不好的设计实践?
    【解决方案2】:

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

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

    【讨论】:

    • 没关系。但随后我将不得不在我的其他子类中保留 QtPorpertyTree 的引用并访问 publicIndexFromItem。同时 QtPropertyTree 正在访问子类的方法。有一个交叉引用的问题,可以解决。但这不是一种糟糕的设计实践吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-15
    • 1970-01-01
    • 2013-09-15
    • 2019-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多