Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QTableView refresh on row insertion

Tags:

c++

qt

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.

like image 782
Kamath Avatar asked Dec 11 '25 13:12

Kamath


1 Answers

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.

like image 55
Daniel Vrátil Avatar answered Dec 14 '25 10:12

Daniel Vrátil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!