QSqlTableModel rowCount doesn't change after row delete

  • I was developing a small qt quick app for clients management. I have encountered a problem that I have described here https://forum.qt.io/topic/67287/tableview-how-to-delete-a-row/2

    Investigating the problem, I have discovered that it is a bug in QSqlTableModel. I implemented the following code and ran it

    #include <QtSql/QSqlTableModel>
    #include <QDebug>
    #include <QtSql/QSqlDatabase>
    #include <QMessageBox>
    #include <QApplication>
    int main(int argc, char *argv[])
        QApplication app(argc, argv);
        QString dbName(app.applicationDirPath());
        QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
        if (!db.open()) {
            QMessageBox::critical(0, qApp->tr("Impossibile aprire il database"), "", QMessageBox::Cancel);
            return 0;
        QSqlTableModel dataModel;
        qDebug() << dataModel.rowCount();
        qDebug() << dataModel.rowCount();

    As you can see, it interfaces with the Sqlite db and tries to delete a row. The problem is that both qDebug statements give the same number for rowCount. So you remove a row, but the rowCount doesn't change. This confuses the TableView qml control that I am using in the other program and forces it to show empty rows at the end of the table.

  • As the documents for QSqlTableModel::removeRows(not removeRow) says,

    "Deletions are submitted immediately to the database. The model retains a blank row for successfully deleted row until refreshed with select()."

    QSqlTableModel doesn't reimplement removeRow, but I think it works the same. So you should call select()

Log in to reply

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