How to get the number of items of a QTreeWidget

拜拜、爱过 提交于 2019-12-05 14:56:16

You can write a recursive function that will run over the hierarchy and count all visible items. For example:

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

And the usage:

QTreeWidget tw;
// Add items
[..]
int visibleItemsCount = treeCount(&tw);

Just ran into this myself for PyQt. There's actually a much easier solution, you just need to use the QTreeWidgetItemIterator (which already loops over all items in the tree, as the name suggests). I don't know C++ so here's my python solution, however the theory is obviously the same. You want to iterate over the QTreeWidget and any items which are expanded should be counted. Namely:

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!