Зависает GUI при изменении QProgressBar из QThread с помощью сигналов.
Код:
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QFileDialog>
#include <QThread>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
public slots:
private slots:
void on_pushButton_1_clicked();
private:
Ui::Widget *ui;
};
#endif // WIDGET_H
#include "widget.h"
#include "worker.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_pushButton_1_clicked()
{
QString filename = QFileDialog::getOpenFileName(
this,
"Открыть файл",
"",
"Все файлы (*.*)",
nullptr,
QFileDialog::DontUseNativeDialog
);
if (filename != QString("")) {
ui->label_2->setText(filename);
QThread *thread = new QThread;
Worker *worker = new Worker(filename);
worker->moveToThread(thread);
connect(thread, &QThread::started, worker, &Worker::process);
connect(worker, &Worker::finished, thread, &QThread::quit);
connect(worker, &Worker::finished, worker, &QObject::deleteLater);
connect(thread, &QThread::finished, thread, &QObject::deleteLater);
connect(worker, &Worker::progressRangeChanged, ui->progressBar, &QProgressBar::setRange);
connect(worker, &Worker::progressValueChanged, ui->progressBar, &QProgressBar::setValue);
thread->start();
}
}
#ifndef WORKER_H
#define WORKER_H
#include <QObject>
#include <QDebug>
#include <QFile>
#include <QThread>
class Worker : public QObject
{
Q_OBJECT
QString workerFilename;
public:
explicit Worker(QString filename, QObject *parent = nullptr);
virtual ~Worker();
signals:
void finished();
void error(QString err);
void progressRangeChanged(int min,int max);
void progressValueChanged(int progress);
public slots:
void process();
};
#endif // WORKER_H
#include "worker.h"
Worker::Worker(QString filename, QObject *parent) : QObject(parent)
{
workerFilename = filename;
}
Worker::~Worker()
{
}
void Worker::process()
{
// qDebug()<<workerFilename;
QFile file(workerFilename);
int fileSize = file.size();
emit progressRangeChanged(0, fileSize);
for (int i = 0; i <= fileSize; i++) {
emit progressValueChanged(i);
}
emit finished();
}
QProgressBar обновляется. GUI виджета зависают, окно нельзя переместить.
Подскажите, пожалуйста, в чем ошибка.
emit progressValueChanged(i);
в 1 мс и проверьте