1.线程类workerthread.h
#ifndef WORKERTHREAD_H
#define WORKERTHREAD_H
#include <QThread>
class WorkerThread : public QThread
{
Q_OBJECT
public:
WorkerThread(QObject *parent = 0);
protected:
void run();
signals:
void done();
};
#endif // WORKERTHREAD_H
2.workerthread.cpp 用线程处理一个很耗时的循环,防止界面UI主线程卡顿
#include "workerthread.h"
WorkerThread::WorkerThread(QObject *parent):QThread(parent)
{
}
void WorkerThread::run()
{
for(int i=0;i<1000000000; i++);
emit done();
}
3.mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
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;
};
#endif // MAINWINDOW_H
4.3.mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "QWidget"
#include "QVBoxLayout"
#include "QLCDNumber"
#include "QTimer"
#include "QPushButton"
#include "workerthread.h"
#include "work.h"
#include "QPointer"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
QWidget *widget = new QWidget(this);
QVBoxLayout *layout = new QVBoxLayout;
widget->setLayout(layout);
QLCDNumber *lcd = new QLCDNumber(this);
layout->addWidget(lcd);
QPushButton *btn = new QPushButton(tr("start"),this);
layout->addWidget(btn);
setCentralWidget(widget);
QTimer *timer = new QTimer(this);
connect(timer , &QTimer::timeout,[=](){static int sec = 0; lcd->display(QString::number(sec++));});
WorkerThread *wthread = new WorkerThread(this);
connect(wthread,&WorkerThread::done,timer,&QTimer::stop);
//connect(wthread,&WorkerThread::finished,wthread,&WorkerThread::deleteLater);
connect(btn,&QPushButton::clicked,[=](){
timer->start(10);
wthread->start();});
}
MainWindow::~MainWindow()
{
delete ui;
}