I am trying to connect my Qt application to a database. Since I have a GUI, of course the only way to do this is in a separate thread. I found out that I can do it via QtConcurrent::run
. Here is my code:
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();
}
It works but I am not able (obviously) to get any data out of the process. For example, I would like to know if the connection succeeded and it would be ideal if I could get it through the slot.
I could add the watcher
as a member of the class and query it from the slot but this approach would be tedious for many async task I believe.
What should I do?