Saving expanded state of QTreeView



  • What is the proper way of saving the expanded state of a QTreeView? I would like to store it so I can restore it later on. I don't need to be able to restore it across restarts of the application itself.

    I thought that I would use QAbstractItemModel::persistentIndexList() to get a list of all items, iterate through them in my custom QTreeView and save the indexes which are expanded in a QList<QModelIndex>.
    Later on I would simply iterate through that list and call QTreeView::expand() on every index in that list.
    Is that a good idea?

    How comes that QAbstractItemModel::persistentIndexList() is protected anyway? That looks like I shouldn't use it outside of my custom model.
    Is there a more proper way to get a list of all indexes in a treeview/model?


  • Moderators

    QAbstractItemModel::persistentIndexList() does not return the list of all items. It returns the list of all items stored as persistent indices. If you haven't created any persistent indices this list will be empty. The usual use case is to create such index to "monitor" certain index from outside the model. From that perspective knowing how many other persistent indices exist is considered model internal and should not really be queried (thus it's kept protected).
    You can think of persistent indices as something along the way of QPointer, only for QModelIndex not QObject. I don't think it's a good idea to keep a lot of them as they are kinda heavy.

    One way to approach the problem would be to keep expansion state as part of your model data under a custom role. You would then implement in your model setData() for that role to store the state and data() to retrieve it and query/apply whenever you need to.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.