线程类:注意定义信号发送函数(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));
}
显示效果: