Qt学习之QThread类

QThread类

一、简介
QThread子线程类,是对象管理程序中的一个控制线程。QThread在run()中开始执行。默认情况下,run()通过调用exec()启动事件循环。并在线程中运行Qt事件循环。
二、实现方式
1.QThread类的run()
实现方法:
新建一个集成QThread的类,重写虚函数run,通过run启动线程。
实例:

class workThread:public QThread{
    
    
	Q_OBJECT
	potected:
	void run();//虚函数run
};
void workThread::run(){
    
    ...}

2.QThread类的moveToThread()
实现方法:
创建一个继承QObject类,然后new一个QThread,并把创建好的类通过moveToThread()到子线程中。然后start()子线程,这样就实现一个子线程。主线程通过发送信号,调用创建好的类的方法,从而实现在子线程中的计算。
实例:
workThread.h

class workThread:public QObject{
    
    
	Q_OBJECT
	public:
	signals:
	void sendData(const QString str);
	public slots:
	void getId(){
    
    
	qDebug() << ":now the device is" << QThread::currentThread();
	emit(setData("Hello"));}
};

contorlThread.h

class contorlThread:public QObject{
    
    
	Q_OBJECT
	public:
    contorlThread(QWidget *parent = Q_NULLPTR);
    ~contorlThread();
	signals:
	void openWork();
	slots:
	void getData(const QString str);
	private:
	workThread *work;
	QThread thread;
};

contorlThread.cpp

contorlThread::contorlThread(QWidget *parent)
    : QMainWindow(parent)
{
    
    
    ui.setupUi(this);
    work = new workThread();
    work->moveToThread(&thread);//将任务放到线程中
    connect(this, &contorlThread::openWork, work,&workThread::getId);//获取当前线程的任务id
    connect(&thread, &QThread::finished, work, &QObject::deleteLater);//线程停止发给QObject让他自己销毁
    connect(work, &workThread::sendData, this, &contorlThread::getData);//执行线程任务并将数据返回
    thread.start();//开启子线程
}
void contorlThread::getData(const QString str){
    
    
		qDebug()<<"the info has been get:"<<str;
}
contorlThread::~contorlThread(){
    
    
	thread.quit();
	thread.wait();
}

main.cpp

#include <csignal>
#include <QThread.h>
#include<qdebug.h>
int main(int argc, char *argv[])
{
    
    
    QApplication a(argc, argv);
    contorlThread w;
    w.openWork();
    return a.exec();
}

结果为:
结果图
三、退出线程方式
1.强制停止

QThread thread;
thread.terminate();//强制终止线程
thread.wait();// 调用wait后先调用finished信号对应的槽函数,执行完成后再往下走

2.安全停止
停止使用thread启动的事件循环线程(也就是退出循环事件)

QThread thread;
thread.quit();
thread.wait();// 调用wait后先调用finished信号对应的槽函数,执行完成后再往下走

补充信息,查看之后更清晰
Qt的多线程技术,巨详细,很值得一看
QThread的详解,巨详细,很值得一看

猜你喜欢

转载自blog.csdn.net/m0_56626019/article/details/129837712
今日推荐