QT中通过创建一个继承于QThread的类,实现其中的虚函数void run()的方式来使用线程。
使用方式
1.创建一个继承于QThread的类
2.定义一个bool类型的变量,和StopThread函数,让外部能够控制线程的结束
2.重写虚函数void run()
3.调用start启动
4.在关闭对话框的时候(closeEvent事件)关闭并等待线程的退出
#include <QThread>
class MyThread : public QThread
{
Q_OBJECT
public:
MyThread(QObject* parent = nullptr);
void StopThread();
protected:
void run();
signals:
void connter();
private:
bool stop;
};
#include "mythread.h"
MyThread::MyThread(QObject* parent)
{
stop = false;
}
void MyThread::StopThread()
{
stop = true;
}
void MyThread::run()
{
while (!stop) {
emit connter();
msleep(1000);
}
quit();
}
myThread = new MyThread();
void Thread::closeEvent(QCloseEvent *event)
{
MyThread *thread = this->findChild<MyThread*>();
if(thread == nullptr)
return;
if(thread->isRunning())
{
thread->StopThread();
thread->wait();
}
event->accept();
}