问题
I'm writing a Qt application where different models can insert/delete/update the same table. When one model changes the database, I would like the other models to be notified of the change, so they can update their views accordingly.
It seems that the best way to monitor inserts, deletes and updates in SQLite is to use QSqlDriver::subscribeToNotification
and then react to the notification signal. I know the syntax is along the lines of:
db.driver()->subscribeToNotification("anEventId");
However, I'm not sure what anEventId
means. Is anEventId
a constant provided by SQLite or do I code these specific events into SQLite using triggers or something else and then subscribe to them?
回答1:
The subscribeToNotification
implementation in the Qt sqlite driver relies upon the sqlite3_update_hook function of the sqlite C API. The Qt driver, however, is not forwarding the operation performed, just the table name, and that should be the misterious anEventId argument to pass to subscribeToNotification
. In short, you can listen to events occurring in any table (given it is a rowid table, but it generally is) passing the table name to the subscribeToNotification
method. When your slot catches the notification
signal, though, you only know that an operation occurred in that table, but (sadly) Qt won't tell you which one (INSERT, UPDATE, or DELETE).
So, given a QSqlDriver * driver
:
driver->subscribeToNotification("mytable1");
driver->subscribeToNotification("mytable2");
driver->subscribeToNotification("mytable3");
then in your slot:
void MyClass::notificationSlot(const QString &name)
{
if(name == "mytable1")
{
// do something
}
else if(name == "mytable2")
{
//etc...
来源:https://stackoverflow.com/questions/52204329/how-to-use-qt-qsqldriversubscribetonotification-with-sqlite3