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 =;
            qDebug() << "Selection: " <<;

    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 not QPersistentModelIndex

    • selection will contain index(0,0) and index(1,0)
    • ui->tablePresets->removeRow(index.row()); removes the first row but index(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 the for loop

  • @VRonin Wow! Thank you very much! I think I couldn't be able to solve this on my self!

Log in to reply