How do I update a row in the model and commit to database?
Solved
General and Desktop
-
@jdent No, to affect the model we need to go via the model!
this is the solution:
QModelIndex index = model->index(0, 1); QString v = model->data(index).toString(); QModelIndex idIndex = index.siblingAtColumn(0); int id = model->data(idIndex).toInt(); v += "???"; bool ok = model->setData(index, v); // this is required!!! ok = model->submit();
-
-
@jdent
You do not need to drop down to accessing the model directly viaQModelIndex
andsetData()
. You can do it via theQSqlRecord
. After you wentrec.setValue(1, val);
you need to call bool QSqlTableModel::setRecord(int row, const QSqlRecord &values) to transfer the altered in-memoryrec
to the model:QSqlRecord rec = tm.record(0); QModelIndex idx = tm.index(0, 3); qDebug() << rec.value(3).toString(); qDebug() << idx.data().toString(); auto val = rec.value(3).toString(); val += "###"; rec.setValue(3, val); qDebug() << rec.value(3).toString(); qDebug() << idx.data().toString(); tm.setRecord(0, rec); qDebug() << rec.value(3).toString(); qDebug() << idx.data().toString();
This shows the underlying model altered after the
tm.setRecord(0, rec);
statement. You can thencommit()
or whatever if you wish.record()
generates a copy of what is in a model row.setRecord()
is required if you alter that and want to write it back to the model row.