使用 QTimer、QThread 和进度条

Posted

技术标签:

【中文标题】使用 QTimer、QThread 和进度条【英文标题】:Work with QTimer, QThread and Progress Bar 【发布时间】:2018-09-03 13:32:47 【问题描述】:

我想在 Ui 线程之外使用计算。计算方法——MainWindow Метод 的私有槽。在计算过程中,对象 OutputData(ProgressBar Window 的字段)中的计算数据会逐渐传输。执行计算的线程也是主窗口的一个字段。

主窗口构造函数,创建线程并将计算的开始连接到线程的开始:

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow) 
ui->setupUi(this);

calculation = new QThread(this);

settings.setToDefault();
outputData.setToDefault();
calculationDone = false;

connect(calculation, SIGNAL(started()), this, SLOT(calculate()));

ui->results_display->setText("Загрузите <b>параметры</b> и начинайте расчёты!");

按钮方法,使用 ProgressBar 启动线程和模式窗口:

void MainWindow::on_calculate_button_clicked() 
ui->results_display->clear();
ui->results_display2->clear();

calculation->start();

///TODO QProgressDialog

ProgressDialog progressDialog(&outputData, this);
progressDialog.setModal(true);
progressDialog.exec();

if (progressDialog.result() == QDialog::Rejected) 
    calculation->terminate();
    QMessageBox::critical(this, "Результат", "Расчёт был остановлен!");
 else 
    if (progressDialog.result() == QDialog::Accepted) 
        calculation->quit();
        QMessageBox::about(this, "Результат", "Готово!");
        
    

模态窗口构造函数设置ProgressBar的参数,创建定时器并设置定时器和更新方法之间的连接:

ProgressDialog::ProgressDialog(OutputData *outputData, QWidget *parent) :
QDialog(parent),
ui(new Ui::ProgressDialog) 
ui->setupUi(this);

data = outputData;

ui->quantity_label->setText("0");
ui->progressBar->setMinimum(0);
ui->progressBar->setMaximum(static_cast<int>(data->outputSettings.aircraftQuantity));

timer = new QTimer(this);
timer->setSingleShot(false);
connect(timer, SIGNAL(timeout()), this, SLOT(update()));
timer->start(50);

ProgressBar 更新方法:

void ProgressDialog::update() 
unsigned long aircraftsDone = data->results.size() + data->unprocessedAircrafts.size();
ui->progressBar->setValue(static_cast<int>(aircraftsDone));
ui->aircraftQunatityDone_label->setText(QString::number(aircraftsDone));
ui->progressBar->repaint();

if (aircraftsDone == data->outputSettings.aircraftQuantity) 
    accept();
   

计算目前运行良好,但没有绘制或更新进度信息。

【问题讨论】:

除了Rathin的回答,值得一读Threading basics。 另外,尝试使用 QFuture 或使用 QThreadPool。进行计算时不需要专用线程。您也应该使用智能指针、std::unique_ptr、shared_ptr、weak_ptr 或 Qt 替代品。 【参考方案1】:

这是因为你的 calculate 方法没有在新线程中被调用。

要使用QThread 在新线程中运行任何方法,您必须使用QObject::moveToThread 将该方法作为公共槽的对象(该对象必须从QObject 类继承)移动到QThread 实例中,然后将您的方法与QThread::started 信号连接。 在您的情况下,您只需在MainWindow 中的calculate 插槽和calculation 中的QThread::started 信号之间设置连接,因此当您调用calculation-&gt;start() 时,您将在您调用的同一线程中触发calculate 方法calculation-&gt;start().

要解决此问题,您应该为您的 calculate 方法创建一个单独的类,然后将此类的对象移动到您的 QThread 内的 MainWindow 构造函数中。

我建议你看看reference中的例子

【讨论】:

OutputData 类可以扮演这种“工人”类的角色吗? 只要继承自QObject,就可以。 感谢您的回答。我以为没有对象不需要提交到流中,它的工作原理和其他编程语言类似,即我可以将方法应用到流中 问题已解决。在析构函数 OutputData 之前添加 virtual 并重新运行 qmake【参考方案2】:

这些是Rhathin's answer 和reference 的示例代码。

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QThread>
#include "calculationworker.h"
#include "progressdialog.h"

namespace Ui 
class MainWindow;


class MainWindow : public QMainWindow

    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
    QThread *calculationThread;
    CalculationWorker *calculationWorker;

signals:
    void startCalculation();
    void stopCalculation();

private slots:
    void on_calculate_button_clicked();
;

#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)

    ui->setupUi(this);

    calculationThread = new QThread( this );
    calculationWorker = new CalculationWorker();

    calculationWorker->moveToThread( calculationThread );

    connect( this, SIGNAL(startCalculation()), calculationWorker, SLOT(calculate()) );
    connect( this, SIGNAL(stopCalculation()), calculationWorker, SLOT(stopCalculation()), Qt::DirectConnection );

    calculationThread->start();


MainWindow::~MainWindow()

    calculationThread->quit();
    calculationThread->wait();
    delete calculationWorker;
    delete ui;


void MainWindow::on_calculate_button_clicked()

    ProgressDialog progressDialog( this );
    connect( calculationWorker, SIGNAL(progress(int, int)), &progressDialog, SLOT(progress(int, int)) );
    connect( calculationWorker, SIGNAL(completed()), &progressDialog, SLOT(completed()) );

    emit startCalculation();

    progressDialog.setModal( true );
    progressDialog.exec();

    if ( progressDialog.result() == QDialog::Rejected ) 
        emit stopCalculation();
     else if ( progressDialog.result() == QDialog::Accepted ) 
        // Accepted
    

calculationworker.h

#ifndef CALCULATIONWORKER_H
#define CALCULATIONWORKER_H

#include <QObject>
#include <QThread> // msleep()

class CalculationWorker : public QObject

    Q_OBJECT
public:
    explicit CalculationWorker(QObject *parent = nullptr);

signals:
    void progress( int processed, int quantity );
    void stopped();
    void completed();

public slots:
    void calculate();
    void stopCalculation();

private:
    bool m_stopFlag;
;

#endif // CALCULATIONWORKER_H

calculationworker.cpp

#include "calculationworker.h"

CalculationWorker::CalculationWorker(QObject *parent) : QObject(parent)




void CalculationWorker::calculate()

    m_stopFlag = false;

    int quantity = 1000;
    for ( int i = 0; i < quantity; i++ ) 
        if ( m_stopFlag ) 
            emit stopped();
            return;
        

        // Do calculation here
        QThread::msleep( 10 );

        emit progress( i, quantity );
    

    emit completed();


void CalculationWorker::stopCalculation()

    m_stopFlag = true;

progressdialog.h

#ifndef PROGRESSDIALOG_H
#define PROGRESSDIALOG_H

#include <QDialog>

namespace Ui 
class ProgressDialog;


class ProgressDialog : public QDialog

    Q_OBJECT

public:
    explicit ProgressDialog(QWidget *parent = nullptr);
    ~ProgressDialog();

private:
    Ui::ProgressDialog *ui;

public slots:
    void progress( int processed, int quantity );
    void completed();
;

#endif // PROGRESSDIALOG_H

progressdialog.cpp

#include "progressdialog.h"
#include "ui_progressdialog.h"

ProgressDialog::ProgressDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ProgressDialog)

    ui->setupUi(this);


ProgressDialog::~ProgressDialog()

    delete ui;


void ProgressDialog::progress(int processed, int quantity)

    ui->progressBar->setMaximum( quantity );
    ui->progressBar->setValue( processed );


void ProgressDialog::completed()

    accept();

【讨论】:

非常感谢您的回答。但我有一个稍微不同的意识形态:计数方法应该只计数,仅此而已,它不应该报告它的进度,只报告它已经完成(停止标志)。 Ui 应该查看计算的数据并对其进行分析。 我移动了一些代码,但不幸的是我得到一个错误:symbol(s) not found in architecture x86-64, linker command failed with exit code 1 当我在继承自 QObject 的类中添加 Q_OBJECT 宏时出现 问题已解决。在析构函数 OutputData 之前添加 virtual 并重新运行 qmake 对不起。我没有完全理解你的代码。我使用 QTimer 发布了another version sample codes,在计算时不会发出进度。【参考方案3】:

这些是另一个版本的示例代码,在计算时不会发出进度。

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QThread>
#include "calculationworker.h"
#include "progressdialog.h"

namespace Ui 
class MainWindow;


class MainWindow : public QMainWindow

    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
    QThread *calculationThread;
    CalculationWorker *calculationWorker;

signals:
    void startCalculation();

private slots:
    void on_calculate_button_clicked();
;

#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)

    ui->setupUi(this);

    calculationThread = new QThread( this );
    calculationWorker = new CalculationWorker();

    calculationWorker->moveToThread( calculationThread );

    connect( this, SIGNAL(startCalculation()), calculationWorker, SLOT(calculate()) );

    calculationThread->start();


MainWindow::~MainWindow()

    calculationThread->quit();
    calculationThread->wait();
    delete calculationWorker;
    delete ui;


void MainWindow::on_calculate_button_clicked()

    ProgressDialog progressDialog( calculationWorker ,this );

    emit startCalculation();

    progressDialog.exec();

    if ( progressDialog.result() == QDialog::Rejected ) 
        // Rejected(Stopped)
     else if ( progressDialog.result() == QDialog::Accepted ) 
        // Accepted
    

calculationworker.h

#ifndef CALCULATIONWORKER_H
#define CALCULATIONWORKER_H

#include <QObject>
#include <QThread> // msleep()

class CalculationWorker : public QObject

    Q_OBJECT
public:
    explicit CalculationWorker(QObject *parent = nullptr);

    int getQuantity();
    int getProcessed();

signals:
    void started();
    void stopped();
    void completed();

public slots:
    void calculate();
    void stopCalculation();

private:
    bool m_stopFlag;
    bool m_stopped;

    int m_processed;
    int m_quantity;
;

#endif // CALCULATIONWORKER_H

calculationworker.cpp

#include "calculationworker.h"

CalculationWorker::CalculationWorker(QObject *parent) : QObject(parent)

    m_quantity = 1000;


int CalculationWorker::getQuantity()

    // Return quantity (data->outputSettings.aircraftQuantity)))
    return m_quantity;


int CalculationWorker::getProcessed()

    // Return processed (data->results.size() + data->unprocessedAircrafts.size())
    return m_processed;


void CalculationWorker::calculate()

    m_stopFlag = false;

    emit started();

    // Calculation
    for ( m_processed = 0; m_processed < m_quantity; m_processed++ ) 
        if ( m_stopFlag ) 
            // emit stopped();
            return;
        

        // Do calculation here
        QThread::msleep( 10 );
    

    emit completed();


void CalculationWorker::stopCalculation()

    m_stopFlag = true;

progressdialog.h

#ifndef PROGRESSDIALOG_H
#define PROGRESSDIALOG_H

#include <QDialog>
#include <QTimer>
#include "calculationworker.h"

namespace Ui 
class ProgressDialog;


class ProgressDialog : public QDialog

    Q_OBJECT

public:
    explicit ProgressDialog( CalculationWorker *worker, QWidget *parent = nullptr);
    ~ProgressDialog();

private:
    Ui::ProgressDialog *ui;
    CalculationWorker *m_worker;
    QTimer *m_progressTimer;

public slots:
    void started();
    void update();
;

#endif // PROGRESSDIALOG_H

progressdialog.cpp

#include "progressdialog.h"
#include "ui_progressdialog.h"

ProgressDialog::ProgressDialog( CalculationWorker *worker, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ProgressDialog),
    m_worker(worker),
    m_progressTimer(new QTimer(parent))

    ui->setupUi(this);

    // Connect started signal from worker
    connect( m_worker, SIGNAL(started()), this, SLOT(started()) );

    // Stop calculation by clicking reject button
    connect( this, SIGNAL(rejected()), m_worker, SLOT(stopCalculation()), Qt::DirectConnection );

    // Connect timeout signal to update
    connect( m_progressTimer, SIGNAL(timeout()), this, SLOT(update()) );

    // Stop the timer when the dialog is closed
    connect( this, SIGNAL(finished(int)), m_progressTimer, SLOT(stop()) );


ProgressDialog::~ProgressDialog()

    delete ui;


void ProgressDialog::started()

    ui->progressBar->setMaximum( m_worker->getQuantity() );
    m_progressTimer->start( 50 );


void ProgressDialog::update()

    ui->progressBar->setValue( m_worker->getProcessed() );

    if ( m_worker->getProcessed() == m_worker->getQuantity() ) 
        accept();
    

【讨论】:

以上是关于使用 QTimer、QThread 和进度条的主要内容,如果未能解决你的问题,请参考以下文章

pyqt使用线程更新进度条

进度条QProgressBar

等待QThread时UI会阻塞/如何正确使用QThread

使用 QMessageBox 时无法使用 QThread 设置父错误

python 多线程 QTimer实现多线程

长按如何使进度条变化Android