Well, I hope this time it is ok for you:
#include <QApplication>
#include <QSqlTableModel>
#include <QSqlQuery>
#include <QSqlDatabase>
#include <QSqlError>
#include <QMainWindow>
#include <QTableView>
#include <QStyledItemDelegate>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.open();
QSqlQuery query(db);
query.exec("CREATE TABLE bouquets (variant TEXT NOT NULL, name TEXT NOT NULL, capacity INT NOT NULL, PRIMARY KEY (name));");
query.exec("INSERT INTO bouquets (variant, name, capacity) VALUES ('A', 'foo', 10);");
QMainWindow window;
QSqlTableModel *model;
model = new QSqlTableModel(&window, db);
model->setTable("bouquets");
model->setEditStrategy(QSqlTableModel::OnRowChange);
model->select();
QTableView tableView;
window.setCentralWidget(&tableView);
tableView.setModel(model);
tableView.setItemDelegate(new QStyledItemDelegate(&tableView));
QObject::connect(model, &QSqlTableModel::beforeInsert, [=](QSqlRecord &record)
{
switch (model->lastError().type())
{
case QSqlError::ConnectionError: qWarning() << "Insert connection error" << model->lastError().text(); break;
case QSqlError::StatementError: qWarning() << "Insert statement error" << model->lastError().text(); break;
case QSqlError::TransactionError: qWarning() << "Insert transaction error" << model->lastError().text(); break;
default: break;
}
});
model->insertRow(model->rowCount());
QModelIndex index = model->index(model->rowCount() - 1, 0);
tableView.setCurrentIndex(index);
tableView.edit(index);
window.show();
return a.exec();
}
I write again the steps:
fill only the "variant" column, press enter and change row
check the (correct) error about the missing "bouquets.name" field is fired
come back to the row, check again the same error is firing (just because we changed the row, ok)
fill the "name" column and press enter
The error is fired again! But we set the column to a value different than NULL. No error should be fired.
Now if you still edit the same column and press again enter it will change (correctly) to the next missing column.
fill the "capacity" column and press enter. The row is submitted but:
a) it should not since we didn't change the row
b) a wrong error ("NOT NULL constraint failed: bouquets.capacity Unable to fetch row") is fired: it makes no sense since the field was set and the row correctly submitted