Search code examples
c++qtloopstreeqtreewidget

QTreeWidgetItemIterator with a "subtree"


I am trying to iterate over a part of a QTreeWidget. So I use a QTreeWidgetItemIterator and the constructor with a QTreeWidgetItem. But the iterator does not visit only the item and its children but "ascend" and continue after the given item.

QTreeWidgetItem *root = topLevelItem(0);  
QTreeWidgetItemIterator it(root);

while (*it)
{
   qDebug() << (*it)->text(0);
   ++it;
}

So I obtain this instead of having only 1x nodes.

node1
    node11
    node12
node2
    node21

Is it normal ? Is it possible to use this iterator to iterate on a node ?

Thanks.


Solution

  • Not very familiar with QTreeWidget, but I rerun something similar, and it seems that their iterator iterates from the starting node to the end of the tree. In this case this should do the job (although a little bit ugly):

    QTreeWidgetItem *root = topLevelItem(0);
    QTreeWidgetItemIterator it(root);
    int nodesCount = 1; //for root, each visited child will update the count
    
    for (int i = 0; i < nodesCount; ++i)
    {
       qDebug() << (*it)->text(0);
       nodesCount += (*it)->childCount; //update the count for this node children
       ++it;
    }