欢迎您的访问
专注架构,Java,数据结构算法,Python技术分享

Qt实战:子线程操作UI界面

子线程操作UI界面有更多中方式,这里使用信号与槽的方式

一:创建线程类

头文件cmythread.h

#ifndef CMYTHREAD_H
#define CMYTHREAD_H
#include <QThread>

class CMyThread : public QThread
{
    Q_OBJECT

public:
    CMyThread();
    void run();

signals:
    // 自定义信号
    void Send2UI(int a);
};

#endif // CMYTHREAD_H

源文件cmythread.cpp

#include "cmythread.h"
#include "Windows.h"
#include <QDebug>

CMyThread::CMyThread()
{

}

void CMyThread::run()
{
    int num = 0;
    while(true)
    {
        Sleep(1000);
        qDebug() << "num :" << num++;

        // 发射信号
        emit Send2UI(num);
    }

}


二:主线程中启动

点击按钮启动线程,连接线程过来的信号,槽函数接收信号

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "Windows.h"

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


}

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

void MainWindow::on_pushButton_clicked()
{
    ch = new CMyThread();
    // 连接线程发过来的信号
    connect(ch, SIGNAL(Send2UI(int)), this, SLOT(ShowInfo(int)));
    ch->start();
    return ;
}

void MainWindow::ShowInfo(int msg)
{
    qDebug() << msg;
}
赞(22) 打赏
版权归原创作者所有,任何形式转载请联系作者;码农code之路 » Qt实战:子线程操作UI界面

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏