Qt~C++多线程 Label跨线程访问数据

本文介绍了如何在C++中使用QThread创建线程,并通过自定义信号Send2UI与UI界面进行数据传递。详细讲解了myThread类的定义、信号的发射与接收,以及在MainWindow中展示槽函数ShowInfo的实现和信号连接。
摘要由CSDN通过智能技术生成

线程类:注意定义信号发送函数(void Send2UI(int num);

头文件:mythread.h

#ifndef MYTHREAD_H
#define MYTHREAD_H

#include <QThread>

class myThread : public QThread
{
    Q_OBJECT
public:
    myThread();
protected:
    void run();
signals:
    // 自定义信号
    void Send2UI(int num);
};

#endif // MYTHREAD_H

CPP文件: mythread.cpp

#include "mythread.h"
#include<QDebug>
myThread::myThread()
{

}

void myThread::run()
{
    int n=0;
    while (true)
    {
            qDebug()<<n++<<endl;
            // 发射信号
            emit Send2UI(n);
            msleep(50);//延时50ms
    }
}

窗体文件:注意显示槽函数( void ShowInfo(int num);

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QThread>
#include "mythread.h"
namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:

 
    void on_btnStart_Thread_clicked();
    void ShowInfo(int num);

private:
    Ui::MainWindow *ui;
   
    bool threadStatus=false;
    myThread *mythread=new myThread();
};

#endif // MAINWINDOW_H

cpp文件:注意连接槽函数( // 连接线程发过来的信号

connect(mythread, SIGNAL(Send2UI(int)), this, SLOT(ShowInfo(int)));  ) 

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPushButton>
#include "ui_mainwindow.h"
#include <QDebug>
#pragma execution_character_set("utf-8")


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{

    ui->setupUi(this);

  
    // 连接线程发过来的信号
    connect(mythread, SIGNAL(Send2UI(int)), this, SLOT(ShowInfo(int)));
}

MainWindow::~MainWindow()
{
    delete ui;
}


//开始线程
void MainWindow::on_btnStart_Thread_clicked()
{
    if(threadStatus)
    {
        mythread->terminate();
        mythread->wait();
        threadStatus=false;
        ui->btnStart_Thread->setText("开始");
    }
    else
    {
        mythread->start();
        threadStatus=true;
        ui->btnStart_Thread->setText("停止");
    }
}
// 槽函数
void MainWindow::ShowInfo(int num)
{
   ui->threadLabel->setText("hello"+QString::number(num));
}

显示效果:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

chilian12321

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值