问题
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.
The main code is as follows:
QSqlRelationalTableModel *model = new QSqlRelationalTableModel(NULL, db);
model->setTable(tableName);
model->select();
tableView->setModel(model);
tableView->show();
回答1:
No, there is no need to use dataChanged()
.
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.
- 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 call
model->select()
in a slot connected to the notification() signal.You can use QSqlDriver::hasFeature(QSqlDriver::EventNotifications) to check if notifications from your database are supported.
来源:https://stackoverflow.com/questions/40188267/how-to-update-qtableview-when-database-updated