[Qt-interest] Remove row in QSqlTableModel fails

Jan janusius at gmx.net
Mon Dec 28 20:02:56 CET 2009


Hi,

I have a problem I don't understand (I hope it is obvious to you).
Removing any row in a tablemodel (with SQLite) will fail if I have 
before tried to remove a row with an ON DELETE RESTRICT constraint.

It seems like revertAll() does not clear the models "cache" and it tries 
to resubmit the failing remove. Even a select() afterwards does not help.

Here is a little example. Why is the second m.removeRow(1) failing?


#include <QtCore/QCoreApplication>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QSqlTableModel>
#include <QDebug>

int main(int argc, char *argv[])
{
     QCoreApplication a(argc, argv);

     QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
     db.setDatabaseName(":memory:");

     if (db.open())
      {
         QSqlQuery q;
         q.exec("PRAGMA foreign_keys=1");

         q.exec("CREATE  TABLE tbl1 (id INTEGER PRIMARY KEY)");
         q.exec("CREATE  TABLE tbl2 (fk INTEGER NOT NULL CONSTRAINT fk 
REFERENCES tbl1 (id) ON DELETE RESTRICT)");

         q.exec("INSERT INTO tbl1 (id) VALUES(1)");
         q.exec("INSERT INTO tbl1 (id) VALUES(2)");
         q.exec("INSERT INTO tbl2 (fk) VALUES(1)");

         QSqlTableModel m;
         m.setTable("tbl1");
         m.select();
         m.setEditStrategy(QSqlTableModel::OnManualSubmit);

         qDebug() << m.rowCount();
         qDebug() << m.removeRow(0);
         qDebug() << m.submitAll();
         qDebug() << m.lastError().text();

         m.revertAll();

         qDebug() << m.rowCount();
         qDebug() << m.match(m.index(0, 0), Qt::DisplayRole, "*", -1, 
Qt::MatchWildcard).at(1).row();
         qDebug() << m.match(m.index(0, 0), Qt::DisplayRole, "*", -1, 
Qt::MatchWildcard).at(1).data();
         qDebug() << m.removeRow(1);
         qDebug() << m.submitAll(); //fails. without rows 32-34 it wont fail
         qDebug() << m.lastError().text();

      }

     return 0;
}




More information about the Qt-interest-old mailing list