如何在 SQLite3 中使用 Qt QSqlDriver::subscribeToNotification?

Jef*_*eff 4 c++ sqlite notifications qt

我正在编写一个 Qt 应用程序,其中不同的模型可以插入/删除/更新同一个表。当一个模型更改数据库时,我希望其他模型收到更改通知,以便他们可以相应地更新其视图。

似乎在 SQLite 中监视插入、删除和更新的最佳方法是使用QSqlDriver::subscribeToNotification通知信号然后对其做出反应。我知道语法是这样的:

db.driver()->subscribeToNotification("anEventId");
Run Code Online (Sandbox Code Playgroud)

但是,我不确定是什么anEventId意思。是anEventIdSQLite 提供的常量还是我使用触发器或其他东西将这些特定事件编码到 SQLite 中,然后订阅它们?

p-a*_*l-o 5

将subscribeToNotification在Qt的实现sqlite的驱动程序依赖于sqlite3_update_hook的功能SQLite的C API。然而,Qt 驱动程序不会转发执行的操作,只是转发表名,这应该是传递给 的神秘 anEventId参数subscribeToNotification。简而言之,您可以监听任何表中发生的事件(假设它是一个rowid 表,但通常是)将表名传递给subscribeToNotification方法。notification但是,当您的插槽捕获信号时,您只知道该表中发生了一个操作,但(遗憾的是)Qt 不会告诉您是哪个操作(插入、更新或删除)。

所以,给定一个QSqlDriver * driver:

driver->subscribeToNotification("mytable1");
driver->subscribeToNotification("mytable2");
driver->subscribeToNotification("mytable3");
Run Code Online (Sandbox Code Playgroud)

然后在您的插槽中:

void MyClass::notificationSlot(const QString &name)
{
    if(name == "mytable1")
    {
        // do something
    }
    else if(name == "mytable2")
    {

    //etc...
Run Code Online (Sandbox Code Playgroud)