Reputation: 115
I am writing a program in Qt that executes some sort of algorithm and I want progress bar on dialog window to change proportionally to number of iteration. The problem is that dialog window doesn't reponse when the algorithm is running. It just unfreezes when the algorithm is ended and shows filled bar. I am updating progress bar to expected value at the beginning of algorithm loop.
Upvotes: 0
Views: 1160
Reputation: 715
The 'proper' way would be to create another thread that would connect via signals/slots to you MainWindow to update the progress bar. For example the thread could emit a signal with an integer with the % progress completed to a slot in your main window that would set the progress bar to that int. http://doc.qt.io/qt-5/thread-basics.html
// main.cpp
#include "mainwindow.h"
#include <QApplication>
#include <QThread>
#include <QDebug>
class Thread : public QThread
{
Q_OBJECT
signals:
void progress( int value );
private:
void run()
{
for(int i = 0; i <= 100; i++ )
{
emit progress( i );
QThread::sleep(1);
}
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
qDebug()<<"From main thread: "<<QThread::currentThreadId();
Thread t;
QObject::connect(&t, SIGNAL(finished()), &a, SLOT(quit()));
QObject::connect(&t, SIGNAL(progress(int)), &w, SLOT(onProgress(int)));
t.start();
return a.exec();
}
// mainwindow.h
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow( QWidget * parent );
~MainWindow();
public slots:
void onProgress( int i );
};
// mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::onProgress( int i )
{
ui->progressBar->setValue(i);
}
Or... One workaround could be to call QCoreApplication::processEvents(); occasionally so the main GUI will 'catch up'. http://doc.qt.io/qt-5/qcoreapplication.html#processEvents
Upvotes: 1