How do I update a row in the model and commit to database?
-
I want to change a column of a QSqlRecord in a model like this:
QSqlRecord rec = model->record(0); auto val = rec.value(1).toString(); val += "###"; rec.setValue(1, val); bool ok = model->submitAll();Is this the correct way?
@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(); -
J jdent has marked this topic as solved on
-
@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 viaQModelIndexandsetData(). 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-memoryrecto 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.