Search code examples
qtpyqtpysideqtreeview

Recursively expand all child items of item in QTreeView


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?


Solution

  • 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);
        }
    }