Recursively expand all child items of item in QTreeView

f.rodrigues picture f.rodrigues · Jan 14, 2015 · Viewed 10.6k times · Source

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?

Answer

vahancho picture vahancho · Jan 14, 2015

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