Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

[SOLVED] remove row from QTableView with QSQLTableModel



  • Hi! I have a QTableView filled using a mySQL database through QSQLTableModel.
    I can edit the values and soon they are updated on the database as expected.
    The problem comes when I try to delete one record, I tried different ways as I found some examples on the Internet. The "best" snippet I found is the following but even this doesn't work.
    What am I doing wrong?
    The record that I want to delete is the currently selected (only one row can be selected at once).

    @ //allBooksModel: QSqlTableModel
    //ui->allBooksTable: QTableView
    QModelIndexList list = ui->allBooksTable->selectionModel()->selectedIndexes();
    QModelIndex index = list.at(0);

    allBooksModel->removeRow(index.row(), index);@
    

    Thanks ;)


  • Lifetime Qt Champion

    Hi,

    IIRC, you should just call removeRow(index.row())



  • Oh wow, the constructor asks also for the QModelndex so i fought a lot for nothing!

    Now I can remove the line, also from the database.. but.. it removes the wrong line!!

    I hope to find out what's the problem!!
    Thanks again



  • Kind of strange problem.
    A wrong row is removed because the elements are sorted just before to delete the row! I'm using QSortFilterProxyModel for sorting and filtering...


  • Lifetime Qt Champion

    You are getting the index from your proxy, you should get the original index from your proxy model using mapToSource



  • Thank you! It works correctly now, but I can still see the empty rows when I delete them. I can solve re-selecting the model, is it the correct way?


  • Lifetime Qt Champion

    AFAIK you should not need to


Log in to reply