Solved Selection error with QTableWidget
-
Hello! I am trying to delete the selected rows in a QTableWidget.
When I select the first two rows by dragging like this:
and I press the delete button which has this code:
void PresetTourConfig::deleteSelectedPresetRows() { QModelIndexList selection( ui->tablePresets->selectionModel()->selectedRows() ); for (int i = 0; i < selection.count(); i++) { QModelIndex index = selection.at(i); qDebug() << "Selection: " << index.data(0); ui->tablePresets->removeRow(index.row()); } }
The qDebug() shows this:
Selection: QVariant(QString, "01") Selection: QVariant(QString, "03")
Does anyone know why this happens?
Thank you very much!!
-
because
QModelIndex
is notQPersistentModelIndex
selection
will containindex(0,0)
andindex(1,0)
ui->tablePresets->removeRow(index.row());
removes the first row butindex(1,0)
did not update so it is still pointing at row number 2 that now contains "03"
to solve, add
std::sort(selection.begin(),selection.end(),[](const QModelIndex& left,const QModelIndex& right)->bool{return left.row()>right.row();});
before thefor
loop -
@VRonin Wow! Thank you very much! I think I couldn't be able to solve this on my self!