#include <QLabel>
#include <QPushButton>
#include <QVBoxLayout>
#include <thread>
#include <chrono>
#include <mutex>
#include <QDebug>
class MyWidget : public QWidget
{
Q_OBJECT
public:
MyWidget(QWidget *parent = nullptr) : QWidget(parent)
{
QVBoxLayout *layout = new QVBoxLayout(this);
label = new QLabel("Result: ", this);
layout->addWidget(label);
QPushButton *button = new QPushButton("Start Task", this);
layout->addWidget(button);
layout->addWidget(new QPushButton("helloworld"));
connect(button, &QPushButton::clicked, this, &MyWidget::startTask);
connect(this,&MyWidget::resultReady,this,&MyWidget::updateResult);
}
~MyWidget()
{
if (workerThread.joinable())
{
{
std::lock_guard<std::mutex> lock(mtx);
running = false;
}
workerThread.join();
}
}
signals:
void resultReady(int);
private slots:
void updateResult(int result)
{
qDebug()<<"执行一次耗时操作";
label->setText("Result: " + QString::number(result));
}
void startTask()
{
if (!workerThread.joinable())//线程未在执行
{
running = true;
workerThread = std::thread(&MyWidget::timeConsumingTask, this);
}
}
private:
QLabel *label;
std::thread workerThread;
std::mutex mtx;
bool running{false};
void timeConsumingTask()
{
for(int i = 0;i < 20;++i)
{
if(running)
{
// 模拟耗时操作
std::this_thread::sleep_for(std::chrono::seconds(3));
std::lock_guard<std::mutex> lock(mtx);
emit resultReady(i);
}
}
}
};
不卡界面