Track selection in QListWidget after undo/redo operations
-
I have a QListWidget containing anywhere from 1 to 511 QListWidgetItems. I can add a new item and perform an undo and the new item is removed and a redo to add it back. This is done by saving the state of the vector containing all the QListWidgetItems. I perform the undo/redo by the following:
QlistWidget->clear();and then reloading the data from the vector.
The problem is if there are selected items in the QListWidget. The selected items must be tracked in the undo/redo operations. I do save the selected items into a QList before clearing the QlistWidget. The problem is re-selecting the item after a redo. Since I clear the list and reload it the QListWidgetItem saved doesn't match the new list so it selects the wrong item in the QListWidget.
I save the selected items by doing the following:
QList<QListWidgetItems*> selectedIndices = QListWidget->selectedItems();then clear the QListWidget:
QListWidget->clear();reload the QListWidget and then set the selected items:
for (QListWidgetItems *items : selectedIndices ) { QListWidget->setCurrentItem(items); } -
I have a QListWidget containing anywhere from 1 to 511 QListWidgetItems. I can add a new item and perform an undo and the new item is removed and a redo to add it back. This is done by saving the state of the vector containing all the QListWidgetItems. I perform the undo/redo by the following:
QlistWidget->clear();and then reloading the data from the vector.
The problem is if there are selected items in the QListWidget. The selected items must be tracked in the undo/redo operations. I do save the selected items into a QList before clearing the QlistWidget. The problem is re-selecting the item after a redo. Since I clear the list and reload it the QListWidgetItem saved doesn't match the new list so it selects the wrong item in the QListWidget.
I save the selected items by doing the following:
QList<QListWidgetItems*> selectedIndices = QListWidget->selectedItems();then clear the QListWidget:
QListWidget->clear();reload the QListWidget and then set the selected items:
for (QListWidgetItems *items : selectedIndices ) { QListWidget->setCurrentItem(items); }@gabello306
But yourselectedIndicesdoes not hold indices! Don't save pointers to anything, and not the wholeQListWidgetItem. Save indexes, or "unique key" if it's appropriate and unique. I don't know whether with QModelIndexList QListView::selectedIndexes() you can save and reuse aQModelIndex, quite possibly not, but since you have a simple list you can just save anintof its index. Of course you also need to restore sort order if that is dynamic.... -
G gabello306 has marked this topic as solved