PDA

View Full Version : Reselect items in QListWidget from QList<QListWidgetItem *>



Tuba
4th April 2012, 15:11
Hi
I've been searching around and am pretty sure this has not been covered.

I am trying to select a list of items in a QListWidget. The list of items is currently in a QList<QListWidgetItem *> (the same as when you use QListWidget->selectedItems). So I basically want to step through the QList and select all items appearing in the QList in the QListWidget.
What is the easies way to do this. I tried a couple of things, but with my best attempt, the program crashes in runtime :(.

If it helps, the purpose for the code:
The user selects a number of items in the QListWidget. He can then move the selected items up or down in the list (simply change the order). This is done by clicking on a button. The button then emits a signla that changes the order of the underlying QList containing the actual items in the entire QListWidget.
At the same time, the user's current selection is saved to reselect these (hopefully...) after the order is changed.
After the order is changed, the QListWidget is updated by first clearing it and then adding the entire reordered list. At this point I want to select the previous selection for the user so that he can click the "Change Order Button" again, without having to reselect the item to move.

What I currently have: (I hope the code displays correctly)


if ( _selection.count() > 0 )
{
foreach(QListWidgetItem *item, _selection)
{
ui->lstIncludedFolder->setCurrentItem(item, QItemSelectionModel::Select);
}
}

_selection is the QList<QListWidgetItem *> list of previously selected items.
lstIncludedFolder is the QListWidget containing the entire list of items.

Thanks

wysota
4th April 2012, 16:06
First, there is a difference between a "current" item and a "selected" item. You want the latter, not the former. Then instead of fighting with QListWidget, you should use QListView with your own model that operates on the underlying list you already have. Then you wouldn't need to do anything as the model-view framework would do everything for you (at the cost of having to implement your own model).

Tuba
4th April 2012, 19:53
Thanks Wysota. I'll give that a try