子线程操作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;
}