Recursively expand all child items of item in QTreeView
Asked Answered
H

2

7

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?

Hiroshima answered 14/1, 2015 at 14:11 Comment(0)
G
12

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);
    }
}
Gaeta answered 14/1, 2015 at 14:20 Comment(11)
But how do I get the initial QModelIndex?Hiroshima
@f.rodrigues, what is the use model? How do you need to expand it? By clicking on a node?Gaeta
The model is a QStandardItemModel(), and a node is expanded by clicking in it.Hiroshima
@f.rodrigues, ok, than handle the QAbstractItemView::clicked() signal of your tree view and you will get the initial index of the clicked node.Gaeta
The clicked only gives emits its signal when I click on the name, not on the decorator '>' beside it.Hiroshima
@f.rodrigues, what about QTreeView::expanded() signal instead? But be careful, because the expandChildren() function I proposed will cause the expanded signal emition too.Gaeta
Oh yeah, the expanded worked, I was using it, but with a lambda and it was losing the index in the process.Hiroshima
Working fine, just a minor complain. The animation of the expanding is complety gone, is there a way to fix this?Hiroshima
@Hiroshima 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.Pipistrelle
Should it not be view->isExpanded (Qt 5.6) and do you really think calling it is more efficient than just calling expand?Asaph
@DaRich, expand is already optimised for the case that the tree item is expanded. So the check is not necessary.Blenheim
S
4

Starting from Qt 5.13 QTreeView::expandRecursively is available

Shropshire answered 7/11, 2019 at 13:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.