数据库更新时如何更新QTableView? [英] How to update QTableView when database updated?
问题描述
我使用QSqlRelationalTableModel
从数据库中提取数据,并使用tableView
显示它.现在,当我更新我的数据库时,如何自动更新 tableView
以显示它?我知道我需要使用函数 dataChanged()
来自动进行此操作,但我不知道如何使用它?任何建议将不胜感激.
I use QSqlRelationalTableModel
to extract data from database, and use tableView
to show it. Now, when I update my database, how to update tableView
automatically to show it? I know i need to use function dataChanged()
to make this automatically, but i do not know how to use it? Any suggestion will be appreciated.
主要代码如下:
QSqlRelationalTableModel *model = new QSqlRelationalTableModel(NULL, db);
model->setTable(tableName);
model->select();
tableView->setModel(model);
tableView->show();
推荐答案
不,不需要使用dataChanged()
.
你只需要调用QSqlRelationalTableModel::select()
每当数据库更新时.这将从数据库重新填充模型,并自动更新使用它的视图.
You just need to call QSqlRelationalTableModel::select()
whenever the database gets updated. This will re-populate the model from the database, and update the views that are using it automatically.
- 如果数据库是从您的应用程序中更新的,您只需在应用程序中执行更新查询后调用
model->select()
即可.立> 如果数据库是从另一个应用程序更新的,则必须使用类似 PostgreSQL 的事件通知系统,使用
QSqlDriver::subscribeToNotification()
并在连接到notification()
信号.
- If the database is updated from within you application, you can just call
model->select()
after the update queries get executed in your application. If the database is updated from another application, you'll have to use something like PostgreSQL's event notification system, subscribe to the notification from your application using
QSqlDriver::subscribeToNotification()
and callmodel->select()
in a slot connected to thenotification()
signal.
您可以使用 QSqlDriver::hasFeature(QSqlDriver::EventNotifications)
检查是否支持来自您的数据库的通知.
You can use QSqlDriver::hasFeature(QSqlDriver::EventNotifications)
to check if notifications from your database are supported.
这篇关于数据库更新时如何更新QTableView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!