PDA

View Full Version : Retrieve selected indices from a QListWidget



avh
2nd June 2008, 22:31
If the user has selected multiple items in a QListWidget (contiguously or otherwise), is there any way to get a list (std::vector, preferably, or, better yet, an std::vector<bool> with 1's in the appropriate indices) of the selected rows without doing something like the following?



QList<QListWidgetItem*> selection = listWidget->selectedItems();
int S = selection.size();
std::vector<int> indices;
for(int i = 0; i < S; i++) indices.push_back(listWidget->row(selection[i]));


virtual QModelIndexList QAbstractItemView::currentIndexes()

looks like it might be what I want, but it doesn't seem to be re-implemented for QListWidget or QListView

mcosta
5th June 2008, 15:02
If you want a list of selected indexes, try this



QModelIndexList indexes = listWidget->selectionModel()->selectedIndexes();

std::vector<int> indexList;
foreach(QModelIndex index, indexes)
{
indexList.push_back(index.row());
}


For a list of boolean, try this



QItemSelectionModel* selectionModel = listWidget->selectionModel();
QAbstractListModel* model = qobject_cast<QAbstractListModel*>(listWidget->model());

if(model == 0)
{
QMessageBox::critical(this, "Error", "Wrong conversion");
}
std::vector<bool> indexes;
bool selected = false;
for(int row = 0; row < model->rowCount(); ++row)
{
selected = selectionModel->isSelected(model->index(row));
indexes.push_back(selected);
}