I encounter a strange behavior when I try to update an SQLite database through a view. Depending on which edit strategy I use, I can either update the view, or update the database, but I don't manage to update the database and have the view display the new value.
Essentially, I use the following code:
auto sdb = QSqlDatabase::addDatabase("QSQLITE");
sdb.setDatabaseName("database.db");
QSqlTableModel *model = new QSqlTableModel(0, sdb);
model->setTable("table");
//model->setEditStrategy(QSqlTableModel::OnFieldChange);
model->setEditStrategy(QSqlTableModel::OnManualSubmit);
model->select();
QTableView *tv = new QTableView();
tv->setModel(model);
tv->show();
// I'm not sure, this connect statement is needed.
// Either way, it does not change the behavior of the problem I observe
connect(model,
SIGNAL(dataChanged(const QModelIndex &,
const QModelIndex &,
const QVector<int> &)),
tv,
SLOT(dataChanged(const QModelIndex &,
const QModelIndex &,
const QVector<int> &)));
When I use QSqlTableModel::OnManualSubmit
The view changes, but the underlying database does not get updated. I.e. restarting the application (or reloading the database) does not have the field updated. Which is obvious I guess, because I would have to manually 'submit' the changes to the underlying DB.
When I useQSqlTableModel::OnFieldChange
After hitting enter after editing the view, the view (for the edited row) becomes blank. The underlying DB gets updated, I can see that in the DB, but somehow the view does not get the new value.
It seems my problem was the missing 'PRIMARY KEY' on one of the columns in the SQLite database. Through editing the view, the database could be successfully updated but somehow the changes did not get properly forwarded to the view
Creating a new table with one of the columns being the primary key, solved the problem.