使用qt多线程,实现向主线程循环发送一个数并显示到textBrownser
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "thread_1.h" //引用线程头文件
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
Ui::MainWindow *ui;
Thread_1 thread_1;
private slots:
void on_submitNewNum(int num); //接收到数字的更新
void on_threadStart(); //线程开始后主线程的状态
void on_threadFinished();
void on_btStar_clicked(); //按键点击后的操作
void on_btexit_clicked();
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(&thread_1,SIGNAL(started()),this,SLOT(on_threadStart()));
connect(&thread_1,SIGNAL(threadFinished()),this,SLOT(on_threadFinished()));
connect(&thread_1,SIGNAL(submitNum(int)),this,SLOT(on_submitNewNum(int)));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_submitNewNum(int num)
{
ui->textBrowser->append(QString::asprintf("线程循环第%d次",num));
}
void MainWindow::on_threadStart()
{
ui->textBrowser->append("线程启动!");
ui->btStar->setDisabled(true);
ui->btexit->setDisabled(false);
}
void MainWindow::on_threadFinished()
{
ui->textBrowser->append("线程结束!");
ui->btexit->setDisabled(true);
ui->btStar->setDisabled(false);
}
void MainWindow::on_btStar_clicked()
{
thread_1.start();
}
void MainWindow::on_btexit_clicked()
{
thread_1.threadStop();
}
thread_1.h
#ifndef THREAD_1_H
#define THREAD_1_H
#include <QThread> //引用头文件
class Thread_1 : public QThread //类Thread_1 继承 QThread类
{
Q_OBJECT
public:
explicit Thread_1();
void threadStop();
private:
//int num; //用到的变量
//bool threadState = true;
bool stop_flag;
protected:
void run() Q_DECL_OVERRIDE; //重写run()
signals:
void submitNum(int num); //用于传递run方法里更新的数据
void threadFinished();
};
#endif // THREAD_1_H
thread_1.cpp
#include "thread_1.h"
Thread_1::Thread_1()
{
}
void Thread_1::threadStop()
{
stop_flag = true; //结束信号
}
/* 线程运行内容 */
void Thread_1::run()
{
int num = 0;
stop_flag = false;
while (!stop_flag){
num++;
emit(submitNum(num));
msleep(20);
}
emit threadFinished(); //提交结束信号
quit(); //结束线程
}
ui