PDA

View Full Version : QListWidget multi selection



user
6th February 2008, 02:58
I have a dialog window which comes up with a list of items in a QListWidget * listWidget.
The Dialog consists of the displayed list and OK/Cancel buttons.
I set the selection to ExtendedSelection and now I can select multiple items from the list.
When a selection is made (signal: itemSelectionChanged) I use:


QItemSelectionModel * selections = listWidget->selectionModel();
QModelIndexList indexes = selections->selectedIndexes();

This code gives me the selected items that I then pass from the dialog (which will be closed) to another function which uses the info and saves the list as integer indexes.
I use integer indexes since I have to use the location in the list for other purposes.

My problems is:
I want to select items in the listWidget when the dialog is opened.
That way, if the user selected items once before, the next time he opens the dialog, the previous selection will be presented for him to change or leave as is.

Should I save the QModelIndexList from before or is there a better way?
e.g what is the right way to select items 2-5,6 in my list?

jpn
6th February 2008, 07:36
Should I save the QModelIndexList from before or is there a better way?
e.g what is the right way to select items 2-5,6 in my list?
QModelIndex is a temporary object. It shouldn't be stored because it might get invalid as soon as the model changes. I'd suggest identifying the items in another way.



// set id
int id = 123;
item->setData(Qt::UserRole, id);




// get selected ids
QList<int> ids;
foreach (QListWidgetItem* item, listWidget->selectedItems())
ids += item->data(Qt::UserRole).toInt();




// set selected ids (inefficient if there are lots of items)
for (int i = 0; i < listWidget->count(); ++i)
{
QListWidgetItem* item = listWidget->item(i);
int id = item->data(Qt::UserRole).toInt();
item->setSelected(ids.contains(id));
}