使用流程
1.创建一个QThread的子类,如 mythread
2.重写保护虚函数run(),在该函数内部编写子线程要处理的具体的业务流程
3.实例化mythread对象
4.调用函数start()启动子线程;
流程示例
1.mythread.h
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QThread>
class MyThread : public QThread
{
Q_OBJECT
public:
explicit MyThread(QObject *parent = nullptr);
protected:
void run();
signals:
// 自定义信号, 传递数据
void curNumber(int num);
public slots:
};
#endif // MYTHREAD_H
2.mythread.cpp
#include "mythread.h"
#include <QDebug>
MyThread::MyThread(QObject *parent) : QThread(parent)
{
}
void MyThread::run()
{
qDebug() << "当前线程对象的地址: " << QThread::currentThread();
int num = 0;
while(1)
{
emit curNumber(num++);
if(num == 10000000)
{
break;
}
QThread::usleep(1);
}
qDebug() << "run() 执行完毕, 子线程退出...";
}
3.main.cpp
#include "mythread.h"
int main()
{
MyThread *subthread = new MyThread;
subthread->start();
return 0;
}