Getting a QTreeWidgetItem List again from QTreeWidget

Patrick Bassut picture Patrick Bassut · Apr 3, 2012 · Viewed 22.2k times · Source

How do i do that? Actually my main goal is to get which checkbox in the QTreeWidget is checked. But this I can do if you guys help me out with that one. Well, I cannot find a method that gives me the QList<QTreeWidgetItem *> again so I could go all over the list and check if the checkboxes are checked(weird sentence, huh?). QTreeWidget::selectedItems() does not do what I want. It actually gets the selected item (which can be just one. So I don't know what the itemS means here. I might be wrong anyway).

My main goal NOW is: go through the QTreeWidget being able to do whatever I want with the items of it.

Thanks in advance.

Answer

Chris picture Chris · Apr 3, 2012

Since you're dealing with a tree, the API is designed to give you access to the QTreeWidgetItems in a tree-structure. Thus there is no direct way to simply get access to every single QTreeWidgetItem directly through Qt's API. There are, however, two ways you can do this:

1) If all of your items (or all the items you care about) are "top-level" then you can do something like this:

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

   // Do something with item ...
}

2) If you need to access every item in the tree, along with that item's children, then a recursive approach may be in order:

doStuffWithEveryItemInMyTree( tree->invisibleRootItem() );

void doStuffWithEveryItemInMyTree( QTreeWidgetItem *item )
{
    // Do something with item ...

    for( int i = 0; i < item->childCount(); ++i )
        doStuffWithEveryItemInMyTree( item->child(i) );
}