Nominate our 2022 Qt Champions!

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

    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 (! {
            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