QTableView refresh on row insertion

c++, qt

Solution

Depends on how you insert new data into the database.

If you simply do `QSqlQuery query("INSERT INTO .... ")` somewhere in the code, then the only way to update `QSqlQueryModel` is to reset it, because `QSqlQueryModel` is not self-updating - it simply runs the query and gives you results. It cannot ask the database to give it "new data", because the database does not know what "new data" are in respect to the model, and there are no "push notifications" from databases (usually).

I would recommend using `QSqlTableModel`, which allows you to also insert new rows, and the model will automatically run the `INSERT` query to save the new data into database. It also allows for modifications (`"UPDATE ..."`).

// Setup the model
QSqlTableModel *model = new QSqlTableModel(this, database);
model->setTable("myTable");
model->setEditStrategy(QSqlTableModel::OnManualSubmit);
model->select(); // will populate the model

...
...

// Insert new row and data
const int row = model->rowCount();
model->insertRows(row, 1);
model->setData(model->index(row, 0), "First column value");
model->setData(model->index(row, 1), "Second column value");
// Commit the new record into database
model->submitAll(); // submit

As you can see, the QSqlTableModel almost completely hides the SQL backing from you and you use it like if you were dealing with an ordinary model.

Problem

In QTableView with QSqlQueryModel, what is the right way to refresh view on new row insertion ? I see that resetting model with view works, but I don't think that's the right way to do it. Simple code snippet should help.

Original source