Solved How do I make a QSqlTableModel and/or the corresponding QTableView react on external changes to the database table?
-
Hello,
I'm evaluating PyQT5 for a project of mine and I'm struggling using the database related things.
I hope this is the right place to ask, if not please point me in the right direction.I have a standalone process that displays the content of a MySQL table in a QTableView.
There is another process, that displays one row of that table in QLineEdit fields and allows to edit and update these values, delete the row or insert a new one.The process with the view checks every 10 seconds for a change in update_time on that table. (Haven't found a better solution for this.)
I've read, that if such a change is detected I should call QSqlTableModel .select(). Which rereads the data.
But in doing this for example on a value update, a before selected row of the QTableView gets unselected and the position of the view changes.
So apparently this is the wrong approach. What is the proper way to reflect changes in the database table and keep the states of the view otherwise unmodified?Thanks for your time!
Frank -
@ChefDeCambuse
This is the right way. In that, the databases don't support "notify", where they would let your app know if the data has changed. So polling from client is probably as good as it gets. In your case if you really wanted, when other process sends updates to database you could make it so it uses some mechanism (e.g. IPC) to let your reading process know it has done so, and that could read the database shortly thereafter, but it would be more work, and only if you are in control of the process which updates.Yes,
QSqlTableModel .select()
is required to re-read all data to refresh your view. If you want to do things like keep a certain row selected, or the view scrolled to a certain place, it is your job to read the state before the update and restore appropriately once the new data has arrived. Qt doesn't offer a "just this row has changed in the database", if you wish to recognize that for the view you'd have to write code to achieve. -
-
Thank you very much!
I've got all in place and up and running.
But I'm still puzzled, that these things are not already included.