Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove a list of selected items in the QListView

How can I remove a list of selected items in the QListView in QT 4.6. Something like this does not work, the iterator becomes invalid:

  QModelIndexList indexes = ui.listview_files->selectionModel()->selectedIndexes();
  foreach(QModelIndex index, indexes)
  {
    model->removeRow(index.row());
  }

removeRows also not suitable, it removes N-items that follows the one given. I use QStandardItemModel to store items.

like image 473
Yury Avatar asked Jul 24 '10 12:07

Yury


2 Answers

QModelIndexList indexes;
while((indexes = ui.listview_files->selectionModel()->selectedIndexes()).size()) { 
    model->removeRow(indexes.first().row()); 
}
like image 178
sje397 Avatar answered Nov 15 '22 09:11

sje397


I don't know if it's a bug in new versions of Qt 4.8 but sje397 solution doesn't work for me (on a QTreeView).

I share the best solution i found which is to sort indexes in descending order and remove row from end to begin.

QModelIndexList indexes = pTreeview->selectionModel()->selectedIndexes();
qSort(indexes.begin(), indexes.end(), qGreater<QModelIndex>());

for(iter = indexes.constBegin(); iter != indexes.constEnd(); ++iter){
   pModels->removeRow((*iter).row(), (*iter).parent());
}
like image 36
SaiyanRiku Avatar answered Nov 15 '22 08:11

SaiyanRiku