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.
If you want to get a list of all QTreeWidgetItem in a QTreeWidget you can do a
QList<QTreeWidgetItem *> items = ui->treeWidget->findItems(
QString("*"), Qt::MatchWrap | Qt::MatchWildcard | Qt::MatchRecursive);
Since you're dealing with a tree, the API is designed to give you access to the QTreeWidgetItem
s 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) );
}
The code below is in Python, but it can be easily translated to C++. I had exactly the same problem as the one described in the question, but I was using PySide (Python Qt binding).
If you want to get a list of all QTreeWidgetItem
s under a given item (including that item itself), use the first function. To get a list of all QTreeWidgetItem
s in a tree, call the second function.
def get_subtree_nodes(tree_widget_item):
"""Returns all QTreeWidgetItems in the subtree rooted at the given node."""
nodes = []
nodes.append(tree_widget_item)
for i in range(tree_widget_item.childCount()):
nodes.extend(get_subtree_nodes(tree_widget_item.child(i)))
return nodes
def get_all_items(tree_widget):
"""Returns all QTreeWidgetItems in the given QTreeWidget."""
all_items = []
for i in range(tree_widget.topLevelItemCount()):
top_item = tree_widget.topLevelItem(i)
all_items.extend(get_subtree_nodes(top_item))
return all_items
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With