You are not logged in.

malcheda

Beginner

  • "malcheda" started this thread

Posts: 2

Location: Germany

Occupation: Mechanical Engineer

  • Send private message

1

Monday, February 23rd 2009, 10:16pm

QTreeView and expand state

Hi there,
I have a QTreeView and several instances of an own model based on QAbstractItemModels. After changing the current model in the QTreeView with setModel, all items are collapsed.
How can I save and restore the expand/collapse state for each model?

Thanks for a hint...
Daniel

2

Wednesday, February 25th 2009, 3:42pm

Is there a good reason for having multiple models ? If I was you, I would use a single model and apply the changes inside the same model. But, if you want to keep multiple models, then look at the following functions :
  • bool QTreeView::isExpanded ( const QModelIndex & index ) const
  • void QTreeView::setExpanded ( const QModelIndex & index, bool expanded )
Mandriva Linux release 2009.0 (Official) for i586
Kernel 2.6.27.10-desktop-1mnb on a Dual-processor i686

malcheda

Beginner

  • "malcheda" started this thread

Posts: 2

Location: Germany

Occupation: Mechanical Engineer

  • Send private message

3

Saturday, February 28th 2009, 3:13pm

The reason for having mulitple models is that in my application the user can load multiple files, whose content is stored in a model instance and displayed in a QTreeView. When the user switches to another file, the respective model is assigned to the QTreeView.

I tried to go through the model via recursion and check the expansion state for each item.
Unfortunately QTreeView::isExpanded always returns true, although items are collapsed...
Despite this, I think it is a rather expensive solution.

4

Saturday, February 28th 2009, 11:14pm

Looking at the tree view's source code, I see that the expanded states are saved inside the tree view itself, using a QList container :

Source code

1
QList<QPersistentModelIndex> expandedIndexes;

Basically, when an item is expanded, its index is added to that expandedIndexes list. When an item is collapsed, its index is removed from that list. Now, the tree view declares this list private -- you cannot access it directly. Your only access functions are those I gave you before : isExpanded() and setExpanded().

And inside setModel(), there's the following instruction :

Source code

1
expandedIndexes.clear();

I see two solutions to your problem :

A/ When unsetting a model, create by your own a list of expanded indexes using isExpanded() and later apply it using setExpanded(). The restore code should start with setUpdatesEnabled(false) and end with setUpdatesEnabled(true).

or

B/ Create as many tree views as tree models.
Mandriva Linux release 2009.0 (Official) for i586
Kernel 2.6.27.10-desktop-1mnb on a Dual-processor i686