1、继承QThread类,重写run函数。此实现方法只有run函数内的代码是运行在子线程内。
代码示例:
#ifndef QDEMOTHREAD_H
#define QDEMOTHREAD_H
#include <QThread>
#include <QDebug>
class QDemoThread : public QThread
{
Q_OBJECT
public:
QDemoThread(QObject* parent = nullptr);
~QDemoThread();
protected:
void run() override;
public:
void stop();
private:
bool flag;
};
#endif // QDEMOTHREAD_H
#include "qdemothread.h"
QDemoThread::QDemoThread(QObject* parent) : QThread(parent)
{
}
QDemoThread::~QDemoThread()
{
}
void QDemoThread::run()
{
flag = true;
while(flag)
{
qDebug() << "thread id:" << QThread::currentThreadId();
sleep(1);
}
}
void QDemoThread::stop()
{
flag = false;
if(isRunning())
{
exit(); // 结束线程
wait(); // 等待退出
}
}
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
demoThread = new QDemoThread(this);
qDebug() << "main thread id:" << QThread::currentThreadId();
}
Widget::~Widget()
{
demoThread->stop(); // 退出线程
delete ui;
}
void Widget::on_pushButton_clicked()
{
if(!demoThread->isRunning())
{
demoThread->start(); // 启动线程
}
}
2、创建一个QThread和QWorker(继承自QObject)类对象,使用moveToThread函数移动到thread中运行,通过thread类start信号和worker槽函数绑定
示例代码:
QWorker类:
#ifndef QWORKER_H
#define QWORKER_H
#include <QObject>
#include <QThread>
#include <QDebug>
class QWorker : public QObject
{
Q_OBJECT
public:
explicit QWorker(QObject *parent = nullptr);
signals:
public slots:
void doWork();
};
#endif // QWORKER_H
#include "qworker.h"
QWorker::QWorker(QObject *parent) : QObject(parent)
{
}
void QWorker::doWork()
{
qDebug() << "thread id:" << QThread::currentThreadId();
}
启动线程:
QWorker* worker = new QWorker();
QThread* thread = new QThread();