Recursively expand all child items of item in QTreeView
12,816
Solution 1
To expand all nodes below the given one, I would do it recursively in the following way (C++):
void expandChildren(const QModelIndex &index, QTreeView *view)
{
if (!index.isValid()) {
return;
}
int childCount = index.model()->rowCount(index);
for (int i = 0; i < childCount; i++) {
const QModelIndex &child = index.child(i, 0);
// Recursively call the function for each child node.
expandChildren(child, view);
}
if (!view->expanded(index)) {
view->expand(index);
}
}
Solution 2
Starting from Qt 5.13
QTreeView::expandRecursively
is available
Author by
f.rodrigues
Art major and hobbyist programmer. Interested in Game-Development and Image-Manipulation(Moving and Still). SOreadytohelp
Updated on June 10, 2022Comments
-
f.rodrigues almost 2 years
I have a QTreeView and I want to expand all child items of a recently expanded item.
I tried using .expandAll(), but it expand all others items also.
I'm having a hard time to get the ModelIndex of the item that was lastly expanded, If i do have it I can recursively expand it's children.
How do I do that?
-
f.rodrigues over 9 yearsBut how do I get the initial QModelIndex?
-
vahancho over 9 years@f.rodrigues, what is the use model? How do you need to expand it? By clicking on a node?
-
f.rodrigues over 9 yearsThe model is a QStandardItemModel(), and a node is expanded by clicking in it.
-
vahancho over 9 years@f.rodrigues, ok, than handle the
QAbstractItemView::clicked()
signal of your tree view and you will get the initial index of the clicked node. -
f.rodrigues over 9 yearsThe clicked only gives emits its signal when I click on the name, not on the decorator '>' beside it.
-
vahancho over 9 years@f.rodrigues, what about
QTreeView::expanded()
signal instead? But be careful, because theexpandChildren()
function I proposed will cause the expanded signal emition too. -
f.rodrigues over 9 yearsOh yeah, the expanded worked, I was using it, but with a lambda and it was losing the index in the process.
-
f.rodrigues over 9 yearsWorking fine, just a minor complain. The animation of the expanding is complety gone, is there a way to fix this?
-
three_pineapples over 9 years@f.rodrigues Getting animations working is probably worthy of another question on SO. I have an idea, but way to long to post in the comments of another answer.
-
DaRich almost 8 yearsShould it not be
view->isExpanded
(Qt 5.6) and do you really think calling it is more efficient than just callingexpand
? -
m7913d about 3 years@DaRich,
expand
is already optimised for the case that the tree item is expanded. So the check is not necessary.