What's the right way to remove multiple indice

2019-05-05 00:37发布

问题:

I was trying to remove all selected indices of a QTableView,

Now I use:

foreach (const QModelIndex & idx, model->selectionModel()->selectedIndexes())
{
    model->removeRow (idx.row()); // Obviously bug
}

There's a obvious problem that once you remove the row, the row id is invalidated, w

As there's no function that takes directly the index (or does the index act like a iterator that will get invalidated when data changed?), I don't know what to do.

回答1:

There is QPersistanceModelIndex class which keeps valid state of index. I tried and it seems to be working.

QList<QPersistentModelIndex> indexes;

foreach (const QModelIndex &i, ui->tableView->selectionModel()->selectedIndexes())
    indexes << i;

foreach (const QPersistentModelIndex &i, indexes)
    ui->tableView->model()->removeRow(i.row());

I hope it will help.



标签: qt model qt4