PDA

View Full Version : Sorting with QTreeview



psh
8th August 2021, 09:27
Hi,
I have created a QTreeView with my implementation of sort/filter model and QStandardItemModel. I have enabled sorting on the QTreeview and sorting the view using sortByColumn().
But, if there is any expanded row in the view, sorting a column collapses all the expanded rows and sorts the view. Although, view is correctly sorted, but I want to have expanded rows state maintained.
Am I missing something in the implementation?

d_stranz
8th August 2021, 16:21
I think your issue is the built-in abstraction that disconnects the model from views of the model. That, is, the same model (or proxy in front of the model) can be shared among multiple views, and in some cases those views are not even of the same type - a tree vs. a table, for example. So the model does not keep any state information about expanded / collapsed nodes because that is specific only to a single view of the model.

When you sort the model, it tells the view that all of the QModelIndex instances it is using the display the model are no longer valid, so the view discards all of the state information it keeps.

In order for you to re-establish the state of the view after sorting, you will have to store this information before sorting (using persistent indexes from the -source- model, not the proxy), sort, and then use this stored information to re-establish the state.

If your view starts out completely collapsed, then all you really need to do is keep track of the changes in state of individual indexes using the QTreeView::expanded() and QTreeView::collapsed() signals, and just keep a list of the expanded indexes (source indexes, using QSortFilterProxyModel::mapToSource()). After the sort, you just go through this list, call QSortFilterProxyModel::mapFromSource() to get the proxy index, and call QTreeView::expand() on that.

You don't need to derive from QTreeView to do this. All of the signals, slots, and other methods can be called from the class that holds the tree view.