QT的多线程编程有两种
1、自定义类继承QThread
第一种是自定义一个类继承于QThread,重写run()方法来实现。然后当需要使用线程的时候你就新建一个自定义对象,然后调用start方法开始运行。
下面的例子是widget里面创建一个线程,然后调用start开始运行,线程运行run方法发送信号,widget接收到信号打印。
#include "mythread.h"myThread::myThread(QThread *parent): QThread{parent}
{}void myThread::run()
{emit showSignal();
}
#ifndef MYTHREAD_H
#define MYTHREAD_H#include <QThread>class myThread : public QThread
{Q_OBJECT
public:explicit myThread(QThread *parent = nullptr);void run() override;signals:void showSignal();};#endif // MYTHREAD_H
#include "widget.h"
#include "ui_widget.h"
#include "mythread.h"Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget)
{ui->setupUi(this);myThread *thread=new myThread();connect(thread,&myThread::showSignal,[=](){qDebug() << "mythread is running";});thread->start();
}Widget::~Widget()
{delete ui;
}
2、moveToThread()方法
这种方法是 自定义一个工作类,然后让这个工作类在线程里面运行,而他和主线程的通信方法,通过信号与槽来实现。
#ifndef WORKER_H
#define WORKER_H#include <QObject>class worker : public QObject
{Q_OBJECT
public:explicit worker(QObject *parent = nullptr);private:signals:public slots:void onbuttonpush();};#endif // WORKER_H
#include "worker.h"
#include <QDebug>#include <QThread>worker::worker(QObject *parent): QObject{parent}
{}void worker::onbuttonpush()
{qDebug()<<"worker::"<<QThread::currentThreadId();
}
#include "widget.h"
#include "ui_widget.h"
#include "mythread.h"
#include "worker.h"
#include <QThread>Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget)
{ui->setupUi(this);worker *work = new worker();QThread *thread = new QThread();work->moveToThread(thread);thread->start();connect(this,&Widget::push,work,&worker::onbuttonpush);
}Widget::~Widget()
{delete ui;
}void Widget::on_pushButton_clicked()
{qDebug()<<"Widget::"<<QThread::currentThreadId();emit push();
}