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:

    0_1530617200313_cee6ccc5-74df-4766-8df2-f8c9e6948193-image.png

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

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.