QSqlTableView does not refresh when use setQuery of QSqlQueryModel with QSqlQuery object as parameter
-
Hello,
I'm reworking my Qt Application (Windows Qt 5.5.1) so that it used prepared QSqlQueries instead simple query strings. The QSqlQueryModel accept both: simple query strings and QSqlQuery objects. My application needs to support MySQL and Sqlite databases so I need to transmit the database when setting a new query
This solution works and as soon the QSqQueryModel receives a new query the connected QSqlTableView refreshed it's content.
QSqlDatabase mySqlDatabase; sqltableModel.setQuery("select id, name from mytable where name = 'Peter'", mySqlDatabase);
But when using the solution using prepared Statements the QSqlTableView does not refresh the content
QSqlDatabase mySqldatabase; QSqlQuery sqlQuery(mySqlDatabase); sqlQuery.prepare("select id, name from mytable where name = :searchstring") sqlQuery.bindValue(":searchstring", "Peter"); sqlTableModel.setQuery(sqlQuery);
The prepared statements are working when I execute them directly. So the SQL statement itself is o.k. but when using it in combination with QSqlQueryModel and QSqlTableView the table view does not get refreshed.
I'm alread trying to call QSqlTableViews clear method and calling directly the QSqlTableViews query directly with
sqlTableModel.query.exec();
It was executed but without refreshing the connected QSqlTableView.
Any idea whats going wrong here?
-
Found the solution by myself. You need to exec the QSqlQuery object BEFORE set it in QSqlQueryModel object then the model is updated and signal it to the connected QSqlTableView
QSqlDatabase mySqlDatabase; QSqlQuery sqlQuery(mySqlDatabase); sqlQuery.prepare("select id, name from mytable where name = :searchstring") sqlQuery.bindValue(":searchstring", "Peter"); if (sqlQuery.exec()) { sqlTableModel.setQuery(sqlQuery); }