QT中子线程(自定义线程)访问UI线程中的控件的方法

您所在的位置:网站首页 子线程创建对象 QT中子线程(自定义线程)访问UI线程中的控件的方法

QT中子线程(自定义线程)访问UI线程中的控件的方法

2024-06-24 01:26| 来源: 网络整理| 查看: 265

本人也是刚学习Qt的小白,也算是做个记录吧,这个例子是用VS2019搭建的Qt环境来实现的,主要是获取当前时间并打印到QTextEdit控件里面。

一、本人所知的Qt中线程的创建方式

1.继承QThread类,然后重新实现该类的run()方法。

2.自定义类通过继承QObject后传入到QThread类中来实现。

在4.8以前都是使用第一种方式,在4.8以后官方推荐第二种方式较多,二者区别其实并不大只是第二种方式更灵活,在这里主要是说说第二种方式。

 二、具体流程及代码片段

1.创建继承自QObject的自定义类

.h文件

#pragma once #include class thTest : public QObject { Q_OBJECT public: explicit thTest(QObject* parent = nullptr); void closeThread(); signals: void sendString(QString);//声明信号 public slots: void startThreadSlot();//线程具体执行的函数 private: volatile bool thisAlive; };

.cpp文件

#include"qtwidgetsapplication.h" #include #include #include #include"thTest.h" thTest::thTest(QObject* parent) :QObject(parent) { thisAlive = false; } void thTest::closeThread() { thisAlive = true; } void thTest::startThreadSlot() { if (thisAlive) { return; } while (thisAlive == false) { QDateTime current_date_time = QDateTime::currentDateTime(); QString current_date = current_date_time.toString("yyyy.MM.dd hh:mm:ss.zzz ddd"); qDebug() append(msg);//具体执行往QTextEdit里面追加文本 } void QtWidgetsApplication::openThreadSlot() { qDebug() moveToThread(thread);//将继承Object的类传入线程 connect(thread, SIGNAL(finished()), thClass, SLOT(deleteLater()));//终止线程时要调用deleteLater槽函数 connect(thread, SIGNAL(started()), thClass, SLOT(startThreadSlot())); //开启线程槽函数 connect(thread, SIGNAL(finished()), this, SLOT(finishedThreadSlot()));//线程结束时调用的槽函数 thread->start();//启动线程 } void QtWidgetsApplication::closeThreadSlot() { qDebug() isRunning()) { thClass->closeThread();//调用自定义类的函数 thread->quit(); thread->wait(); delete thread; thread = NULL; } } void QtWidgetsApplication::finishedThreadSlot() { /*用于线程执行完后,执行这个槽函数里面的代码*/ qDebug()


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3