Frage

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.

War es hilfreich?

Lösung

QModelIndexList indexes;
while((indexes = ui.listview_files->selectionModel()->selectedIndexes()).size()) { 
    model->removeRow(indexes.first().row()); 
}

Andere Tipps

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());
}

Here I've excavated your question in 2016...

The problem with your original solution is that it invalidates indices, i.e. if you want to remove elements with indices 5, 6, and 7, after removing the fifth item, item number six now becomes item number five and so on.

To make your solution work, there's no need to evaluate selectionModel()->selectedIndexes() everytime in your loop. The trick is to start from the end and iterate back to the beginning. If you remove the item number 7 first, items with numbers 5 and 6 will keep their positions.

To give you folks some code:

QModelIndexList selectedIndexes(listView->selectionModel()->selectedIndexes());

for (QModelIndexList::const_iterator it = selectedIndexes.constEnd() - 1;
        it >= selectedIndexes.constBegin(); --it) {
    model->removeRow(it->row());
}

Hope this will help some random googler.

removing by multiple rows is more optimized:

QVector<QItemSelectionRange> ranges = ui.listView->selectionModel()->selection().toVector();
foreach (const QItemSelectionRange& range, ranges) {
    ui.listView->model()->removeRows(range.top(), range.height());
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top