我正在尝试将我的Qt应用程序连接到数据库。当然,因为我有一个GUI,所以唯一的方法就是在一个单独的线程中。我发现我可以通过QtConcurrent::run做这件事。这是我的代码:
MainWindow::MainWindow(QWidget *parent) {
// ...
QFuture<bool> worker = QtConcurrent::run(this, &MainWindow::connectDatabase);
QFutureWatcher<bool> *watcher = new QFutureWatcher<bool>;
connect(watcher, &QFutureWatcher<bool>::finished, this, &MainWindow::databaseConnected);
watcher->setFuture(worker);
}
bool MainWindow::connectDatabase() {
QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL");
db.setHostName("127.0.0.1");
db.setUserName("user");
db.setPassword("pass");
db.setDatabaseName("mydb");
return db.open();
}它可以工作,但我不能(很明显)从进程中获取任何数据。例如,我想知道连接是否成功,如果我能够通过插槽,这将是理想的。
我可以将watcher作为类的成员添加,并从槽中查询它,但是对于我认为的许多异步任务来说,这种方法会很繁琐。
我该怎么办?
发布于 2017-04-17 19:38:50
您必须使worker成为类成员(因为局部变量将在退出构造函数时被删除):
MainWindow::MainWindow(QWidget *parent) {
// ...
m_worker = QtConcurrent::run(this, &MainWindow::connectDatabase);
QFutureWatcher<bool> *watcher = new QFutureWatcher<bool>;
connect(watcher, &QFutureWatcher<bool>::finished, this, &MainWindow::databaseConnected);
watcher->setFuture(m_worker);
}方法2:
MainWindow::MainWindow(QWidget *parent) {
connect(this, &MainWindow::mySignalAboutDBOpen,
this, &MainWindow::databaseConnected, Qt::QueuedConnection);
QtConcurrent::run(this, &MainWindow::connectDatabase);
}
//and in the connectDatabase:
bool MainWindow::connectDatabase() {
//...
bool ret = db.open();
emit mySignalAboutDBOpen(ret);
return ret;
}请注意,QSqlDatabase db变量也是本地变量,在退出connectDatabase()时将被删除。
请参阅Qt::ConnectionType
https://stackoverflow.com/questions/43457063
复制相似问题