PDA

View Full Version : QSqlQueryModel not updating when database changes



Momergil
31st March 2014, 03:59
Hello!

Giving my understading of Qt's model system, I developed a software which displays, in QListViews, the content of a field from a SQLite based table. I imagined that, by using the query model, each time I updated my table, the query would automatically notice it and update the items on the QListView.

For my unhappiness, that didn't ocurr, and now the QListViews are only updated when the software is closed and reopened. Based on this comes my first question: wasn't QSqlQueryModel supposed to update when the database is changed? Is there something lacking? Or this is not the appropriate class to do such a work while there is another class that do so?


Now after noticing this, I tried to find a way to manually update the model, that is, make it call the QSqlQuery once again after the database is updated. But unfortunately (I'm using Qt 5.1) I couldn't find any method to do such work. I even found this¹ topic that talks about this, but it didn't give me any working solution :T So my second question is: is there a way to update the model programatically once I know that the database was changed? And, more specifically, is there a way to do this without having to call a method each time it ocurrs, but in a smarter way? (like reimplement QSqlDatabase with a new signal that is emitted each time the database is changed).


Thanks,

Momergil


¹: http://www.qtcentre.org/threads/29597-The-quot-best-quot-way-to-refresh-a-QSqlQueryModel-when-the-content-of-the-query-changes

ChrisW67
31st March 2014, 05:09
QSqlQueryModel is read-only and reads only when setQuery() is called. Read-write models like QSqlTableModel track changes when they are made through the model.

There is no single mechanism that Qt can use to receive notification from an underlying database engine about external changes that is supported or adaptable across all the databases supported by Qt. Oracle, Postgresql, and Sqlite have mechanisms to announce changes: all different of course. MySql has, AFAICT, no notification mechanism at all. ODBC is a generic abstraction that the Qt abstraction is built on top of: it seems unlikely notifications would make it through. Qt does not expose the notification mechanism in Sqlite if db.driver()->hasFeature(QSqlDriver::EventNotifications) is to be believed. If it were exposed you could use the QSqlDriver functions to subscribe.

You can refresh your QSqlQueryModel by recalling setQuery() with the query(). Calling model->query()->exec() may work (I have not tried). You will probably lose selections in attached views and a few other things.