6

I have created a QTreeWidget, I'm trying to list all the items displayed.

I do not want to go inside the items if the item have child but not expanded. It's really getting the number of Items I can see in the tree.

I have tried :

   for( int i = 0; i < MyTreeWidget->topLevelItemCount(); ++i )
    {
       QTreeWidgetItem *item = MyTreeWidget->topLevelItem(i);
       ...

but this is giving me only the topLevelItem and I want all I can see. In the example, I should be able to count 14 items

enter image description here

4

2 回答 2

5

您可以编写一个递归函数,该函数将在层次结构上运行并计算所有可见项目。例如:

int treeCount(QTreeWidget *tree, QTreeWidgetItem *parent = 0)
{
    int count = 0;
    if (parent == 0) {
        int topCount = tree->topLevelItemCount();
        for (int i = 0; i < topCount; i++) {
            QTreeWidgetItem *item = tree->topLevelItem(i);
            if (item->isExpanded()) {
                count += treeCount(tree, item);
            }
        }
        count += topCount;
    } else {
        int childCount = parent->childCount();
        for (int i = 0; i < childCount; i++) {
            QTreeWidgetItem *item = parent->child(i);
            if (item->isExpanded()) {
                count += treeCount(tree, item);
            }
        }
        count += childCount;
    }
    return count;
}

以及用法:

QTreeWidget tw;
// Add items
[..]
int visibleItemsCount = treeCount(&tw);
于 2015-03-03T11:05:44.140 回答
2

我自己刚刚为 PyQt 遇到了这个问题。实际上有一个更简单的解决方案,您只需要使用QTreeWidgetItemIterator(顾名思义,它已经遍历树中的所有项目)。我不知道 C++ 所以这是我的 python 解决方案,但是理论显然是一样的。您想要遍历 QTreeWidget 并且应该计算任何展开的项目。即:

def count_tems(self):
    count = 0
    iterator = QtGui.QTreeWidgetItemIterator(self) # pass your treewidget as arg
    while iterator.value():
       item = iterator.value()

        if item.parent():
            if item.parent().isExpanded():
                count +=1
        else:
            # root item
            count += 1
        iterator += 1
    return count
于 2018-05-07T19:25:17.283 回答