实现步骤
1.1、自己实现一个子线程类myThread,并继承于QThread类。
1.2、重写子线程类myThread中的虚函数run()。
1.3、在主线程Widget中定义子线程类对象。
1.4、在主线程Widget中连接信号槽,实现子线程于主线程之前通信。
1.5、主线程Widget中使用子线程的start()方法启动子线程。
项目结构
主线程代码
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include "mythread.h"
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:A
explicit Widget(QWidget *parent = 0);
~Widget();
public slots:
//定义槽函数,接收子线程发送来的数据
void recvData(QString data);
private:
Ui::Widget *ui;
//定义子线程对象
myThread *mTh;
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
mTh = new myThread;
connect(mTh, &myThread::sendData, this, &Widget::recvData);
//开启线程
mTh->start();
}
Widget::~Widget()
{
delete mTh;
delete ui;
}
void Widget::recvData(QString data)
{
qDebug()<<"线程处理结果 : "<<data;
}
子线程代码
mythread.h
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QThread>
class myThread : public QThread
{
Q_OBJECT
public:
explicit myThread(QThread *parent = nullptr);
signals:
//定义信号,发送数据给主线程
void sendData(QString data);
public slots:
protected:
virtual void run(); //虚函数,线程处理函数
};
#endif // MYTHREAD_H
mythread.cpp
#include "mythread.h"
myThread::myThread(QThread *parent) : QThread(parent)
{
}
void myThread::run()
{
QThread::sleep(5); //睡眠5s,模拟线程处理业务流程
//将处理结果发送给主线程
sendData("thread finished!");
}
main.cpp
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
实现效果
启动程序5s后,就可以在控制台看到如下输出