2

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?

Community
  • 1
  • 1
Horst Walter
  • 13,663
  • 32
  • 126
  • 228

2 Answers2

4

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:

Vao Tsun
  • 47,234
  • 13
  • 100
  • 132
Balázs Édes
  • 13,452
  • 6
  • 54
  • 89
1

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.

Frank Osterfeld
  • 24,815
  • 5
  • 58
  • 70