子线程如下:
mythread.h:
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QThread>
class myThread:public QThread
{
Q_OBJECT
public:
myThread();
~myThread();
void run() override;
bool m_bStart;
signals:
void updateProgress(const int nNum);
};
#endif // MYTHREAD_H
mythread.cpp:
#include "mythread.h"
myThread::myThread():m_bStart(false)
{
}
myThread::~myThread()
{
}
void myThread::run()
{
int i = 0;
while(m_bStart)
{
i++;
emit updateProgress(i);
msleep(100);
if(i>99)
i=0;
}
}
主线程如下:
mainwindow.h:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "mythread.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
myThread m_thread;
void updateProgress(int nNum);
private slots:
void on_pushButton_clicked();
private:
Ui::MainWindow *ui;
};
#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);
connect(&m_thread,&myThread::updateProgress,this,&MainWindow::updateProgress);
}
MainWindow::~MainWindow()
{
m_thread.m_bStart = false;
m_thread.wait();
delete ui;
}
void MainWindow::updateProgress(int nNum)
{
ui->progressBar->setValue(nNum);
}
void MainWindow::on_pushButton_clicked()
{
m_thread.m_bStart = true;
m_thread.start();
}
主界面上有个按钮和一个进度条
运行效果如下: