QThread 和窗口之间的通信通常通过信号和槽机制来实现
也可以直接通过调用线程中的值
效果图(Dialog To hello; TextLabel To hello)
在主窗口类中创建线程实例,并连接线程发出的信号到主窗口的槽函数。
.h
#ifndef TESTAPP_H
#define TESTAPP_H#include <QDialog>
#include <QThread>namespace Ui {
class TestApp;
}class TestAppThread : public QThread
{Q_OBJECTpublic:QString threadValue;signals:void valueSignals(QString valueStr);protected:void run() override;
};class TestApp : public QDialog
{Q_OBJECTpublic:explicit TestApp(QWidget *parent = nullptr);~TestApp();TestAppThread *m_testAppThread;public slots:void valueReceiver(QString valueStr);private:Ui::TestApp *ui;
};#endif // TESTAPP_H
.cpp
#include "testapp.h"
#include "ui_testapp.h"TestApp::TestApp(QWidget *parent) :QDialog(parent),ui(new Ui::TestApp)
{ui->setupUi(this);m_testAppThread = new TestAppThread;m_testAppThread->threadValue = "hello";connect(m_testAppThread,&TestAppThread::valueSignals,this,&TestApp::valueReceiver);m_testAppThread->start();
}TestApp::~TestApp()
{m_testAppThread->quit();m_testAppThread->wait();delete m_testAppThread;delete ui;
}void TestAppThread::run()
{emit valueSignals(threadValue);
}void TestApp::valueReceiver(QString valueStr)
{this->setWindowTitle(m_testAppThread->threadValue);ui->label->setText(valueStr);
}