Qt利用全局变量让主线程和子线程互传数据

0x00 创建全局变量

  •  Qt在创建全局变量时,全局变量的声明必须在头(H)文件中,全局变量的定义必须在CPP文件中。
#ifndef GLOBALVAR_H
#define GLOBALVAR_H

struct myData{
    bool networkStatus;
};

//声明全局变量
extern myData bigData;

#endif // GLOBALVAR_H
#include "globalvar.h"

//定义全局变量
myData bigData = {false};

0x01 在子线程中给全局变量赋值

#ifndef WORKTHREAD_H
#define WORKTHREAD_H
#include 
#include 
#include "globalvar.h"

class WorkThread : public QThread
{
    Q_OBJECT
public:
    WorkThread();

private:
    void run() override;
};

#endif // WORKTHREAD_H
#include "workthread.h"

WorkThread::WorkThread()
{

}

void WorkThread::run()
{
    if(QProcess::execute("ping 127.0.0.1 -w 1") == 0){
        bigData.networkStatus = true;
    }else{
        bigData.networkStatus = false;
    }
}

0x02 在主线程读取子线程给全局变量赋的值,进行界面响应处理

#ifndef MAINWIDGET_H
#define MAINWIDGET_H

#include 
#include "workthread.h"

QT_BEGIN_NAMESPACE
namespace Ui { class MainWidget; }
QT_END_NAMESPACE

class MainWidget : public QWidget
{
    Q_OBJECT

public:
    MainWidget(QWidget *parent = nullptr);
    ~MainWidget();

private slots:
    void on_btnCheckNetwork_clicked();
    void slotDealData();

private:
    Ui::MainWidget *ui;
    WorkThread* workThread;
};
#endif // MAINWIDGET_H
#include "mainwidget.h"
#include "ui_mainwidget.h"
#include 

MainWidget::MainWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::MainWidget)
{
    ui->setupUi(this);

    workThread = new WorkThread();
}

MainWidget::~MainWidget()
{
    delete ui;
    delete workThread;
}

void MainWidget::on_btnCheckNetwork_clicked()
{
    workThread->start();
    connect(workThread, &WorkThread::finished, this, &MainWidget::slotDealData);
}

void MainWidget::slotDealData()
{
    if(bigData.networkStatus == true){
        ui->lblNetworkStatus->setText("网络正常");
    }else{
        ui->lblNetworkStatus->setText("网络故障");
    }
}

 

你可能感兴趣的:(Qt,qt)