How to get the number of items of a QTreeWidget

Seb picture Seb · Mar 3, 2015 · Viewed 10.8k times · Source

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

Answer

vahancho picture vahancho · Mar 3, 2015

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