Qt C++ GUI not drawing till pooled thread ends

61 Views Asked by At

I'm calling a function on QMainWindow's constructor via QtConcurrent in hope that the GUI will be up and showing while the background IO bound task will be processing in the background:

MainWindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QtConcurrent>
#include <QFuture>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow: public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();
private:
    Ui::MainWindow *ui;
    int init();
};
#endif

MainWindow.cpp

MainWindow::MainWindow(QWidget *parent):QMainWindow(parent),ui(new MainWindow){
    ui->setupUi(this);
    ui->myLabel->setText("");
    ui->progress->setVisible(false);
    QFuture<int>future=QtConcurrent::run(MainWindow::init,this);
    if(future.result()==0){
        qInfo()<<"Init successful";
    }else{
        qInfo()<<"Init not successful";
    }
}

int MainWindow::init(){
    QThread::sleep(4);    //simulate IO task
    return 0;
}

But the GUI doesn't appear until init finishes. How to detach this pooled thread with main thread? Or from where should I run this thread?

EDIT: added QFutureWatcher to constructor but I don't know how to pass the return value of init to another function done:

MainWindow::MainWindow(QWidget *parent):QMainWindow(parent),ui(new MainWindow){
    ui->setupUi(this);
    ui->myLabel->setText("");
    ui->progress->setVisible(false);
    QFutureWatcher<int> watcher;
    QFuture future;
    connect(&watcher,QFutureWatcher<int>::finished,this,done(future.result())));//wrong code; need help here    
    future=QtConcurrent::run(MainWindow::init,this);
}

int MainWindow::init(){
    QThread::sleep(4);    //simulate IO task
    return 0;
}
void done(int val){
    if(val==0){
        qInfo()<<"Init successful";
    }else{
        qInfo()<<"Init not successful";
    }
}
0

There are 0 best solutions below