PDA

View Full Version : How to Sort a QModelIndexList



enricong
10th August 2011, 18:40
I have a QModelIndexList from "selectedRows()" from a table.

How can I sort this list in reverse order so I can use this list to remove rows while keeping the indices valid.

azalea
31st August 2016, 10:56
Although it is pretty late to this thread, I am posting my solution in case I forget in future. :D



QModelIndexList indexlist = this->lastView->selectionModel()->selectedRows();
qSort(indexlist.begin(), indexlist.end(), qGreater<QModelIndex>()); // so that rows are removed from highest index
foreach (QModelIndex index, indexlist) {
index.model()->removeRow(index.row());
}

d_stranz
31st August 2016, 16:04
I was going to propose simply using the QList reverse iterator to go from the end of the list backwards, but that assumes the list is sorted in increasing QModelIndex order in the first place. azalea's code doesn't make that assumption, so it is a better and more general solution.