//*******************主窗口****************************//
------------------------.H---------------------------------
-----------------------------------------------------------
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include
#include
#include
#include
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;
QPushButton *btnStart;
QPushButton *btnStop;
QLabel *label;
work *w;
};
#endif // MAINWINDOW_H
------------------------.CPP-------------------------------
-----------------------------------------------------------
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "qthreadpool.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
btnStart = new QPushButton(this);
btnStart->resize(50,40);
btnStart->move(10,10);
btnStart->setText("start");
btnStop = new QPushButton(this);
btnStop->resize(50,40);
btnStop->move(100,10);
btnStop->setText("stop");
label = new QLabel(this);
label->resize(100,40);
label->move(50,100);
label->setText("0");
w = new work;
connect(w,&work::currentNum,this,[=](int num){
label->setText(QString::number(num));
});
connect(btnStart,&QPushButton::clicked,this,[=](){
if(!w->isRun)
{
QThreadPool::globalInstance()->start(w);
}
});
connect(btnStop,&QPushButton::clicked,this,[=](){
w->changeIsRun();
});
}
MainWindow::~MainWindow()
{
delete ui;
}
//*******************线程类****************************//
------------------------.H---------------------------------
-----------------------------------------------------------
#ifndef WORK_H
#define WORK_H
#include
#include
#include
class work : public QObject, public QRunnable
{
Q_OBJECT
public:
explicit work(QObject *parent = nullptr);
QMutex mutex;
int num;
bool isRun;
void run() override;
signals:
void currentNum(int num);
public slots:
void changeIsRun();
};
#endif // WORK_H
------------------------.CPP-------------------------------
-----------------------------------------------------------
#include "work.h"
#include "qthread.h"
work::work(QObject *parent) : QObject(parent), QRunnable()
{
num = 0;
setAutoDelete(false);
}
void work::run()
{
mutex.lock();
isRun = true;
while(isRun)
{
num += 1;
emit currentNum(num);
QThread::sleep(1);
}
mutex.unlock();
}
void work::changeIsRun()
{
isRun = false;
}