Search code examples
qtqt5qtableviewqsortfilterproxymodelqsqlquerymodel

QTableView with a QSortFilterProxyModel seted on, based on a QSqlQueryModel doesn't update when the data in the database change


I have a complex software that has several tables and forms. I need to join some tables in a QSqlQueryModel and show the result into a QTableView I use a QSortFilterProxyModel to have the ability to search in the QTableView that contain the result When I create the QTableView and set the models, everything is OK, but when in another part of the software the database changes I can't see the data changes in the QTableView.

This is a snippet code:

void form1::setModels()
{
    queryModel = new QSqlQueryModel();
    queryModel->setQuery("SELECT * FROM table1");
    proxyModel = new QSortFilterProxyModel(queryModel);
    proxyModel->setSourceModel(queryModel);
    ui->tableView->setModel(proxyModel);
}

This method is called when I create form1 and it's placed below the database connection and open() call

Before I call form1 with exec I try to do a: (form1 contains the QTableView mentioned)

queryModel->query().exec()

In order to update the query but nothing happens until I close the program and run again.

Is like something in the middle of the model doesn't update properly

If I call setModels() before the form exec method (not only in the constructor of the form), the QTableView show the change correctly but I think that is not the correct way to do an update, I already have the models, and the tableview, I think that I only need to update the query and refresh the QTableView and the QSortFilterProxyModel, but I don't find the way to do that.


Solution

  • but when in another part of the software the database changes I can't see the data changes in the QTableView.

    You need to update the model, then the view will be notified of any changes done. When you change the table table1, you do a reset on this model(reset the model, then query the database).