2
votes

Currently I want to update row items in a QStandardItemModel without losing the sort order and row selection in the respective QTableView.

I have tested two approaches:

  1. Clearing the model by clear() and re-adding the rows "destroys" everything including headers.
  2. Removing and re-adding all rows keeps the headers, but still "destroys" selection and sort order.

I could try to manually to a) remove all rows no longer required and then b) update the items of the changed rows. But is there no easier way?

2
have you tried using QProxyModel? The docs now say that it is outdated, but may serve your purpose - friendzis
I do not see how this would help me. I could update all data on the proxy first, but then? What's the basic idea? - Horst Walter
Proxy should handle selections and sort order and data model just provide the data - friendzis

2 Answers

4
votes

I don't know, how you sorted your data before the update, but please take a look at the QTableView's sortByColumn() function.

As for the selection, if it still keeps disappearing, you can manually put back your selection, where it should be by:

// You access the selected index when the editing starts
QModelIndex index = table->selectionModel()->currentIndex();

//Later when you finished editing, you can select it again
table->selectionModel()->select(index, QItemSelectionModel::Select);

More about this:

1
votes

You can either remove the rows no longer required and add the new ones or manually remember the sort order and which items were selected before clearing. I.e. assign a unique ID (one can use setData() with a custom role for that), retrieve that before clearing from the selected items, and reapply the selection after recreating the items.