5

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?

Phlucious
  • 3,704
  • 28
  • 61
f.rodrigues
  • 3,499
  • 6
  • 26
  • 62

2 Answers2

11

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);
    }
}
vahancho
  • 20,808
  • 3
  • 47
  • 55
  • But how do I get the initial QModelIndex? – f.rodrigues Jan 14 '15 at 14:26
  • @f.rodrigues, what is the use model? How do you need to expand it? By clicking on a node? – vahancho Jan 14 '15 at 14:27
  • The model is a QStandardItemModel(), and a node is expanded by clicking in it. – f.rodrigues Jan 14 '15 at 14:28
  • @f.rodrigues, ok, than handle the `QAbstractItemView::clicked()` signal of your tree view and you will get the initial index of the clicked node. – vahancho Jan 14 '15 at 14:30
  • The clicked only gives emits its signal when I click on the name, not on the decorator '>' beside it. – f.rodrigues Jan 14 '15 at 14:39
  • @f.rodrigues, what about `QTreeView::expanded()` signal instead? But be careful, because the `expandChildren()` function I proposed will cause the expanded signal emition too. – vahancho Jan 14 '15 at 14:40
  • Oh yeah, the expanded worked, I was using it, but with a lambda and it was losing the index in the process. – f.rodrigues Jan 14 '15 at 14:44
  • Working fine, just a minor complain. The animation of the expanding is complety gone, is there a way to fix this? – f.rodrigues Jan 14 '15 at 15:00
  • 1
    @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. – three_pineapples Jan 14 '15 at 23:51
  • 2
    Should it not be `view->isExpanded` (Qt 5.6) and do you really think calling it is more efficient than just calling `expand`? – DaRich Jun 16 '16 at 12:54
  • 1
    @DaRich, `expand` is already optimised for the case that the tree item is expanded. So the check is not necessary. – m7913d Mar 17 '21 at 13:41
3

Starting from Qt 5.13 QTreeView::expandRecursively is available

m7913d
  • 10,244
  • 7
  • 28
  • 56