QT中线程中使用信号和槽传数据

发布于:2025-02-14 ⋅ 阅读:(38) ⋅ 点赞:(0)

mainwindow.h 

#ifndef WORKERTHREAD_H
#define WORKERTHREAD_H

#include <QObject>
#include <QThread>
#include <QQueue>
class WorkerThread : public QThread
{
    Q_OBJECT
public:
    explicit WorkerThread();
private:
    void run() override;  //重新实现run()

signals:
    void sendData(float zhi);

};

#endif // WORKERTHREAD_H

workerthread.cpp 


#include <iostream>
#include "workerthread.h"
#include <QTimer>

WorkerThread::WorkerThread()
{

}


void WorkerThread::run()
{

    std::cout << "Thread started" << std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(5)); // 延时2秒
    std::cout << "Thread finished" << std::endl;
    emit sendData(5.28);
}

mainwindow.h 

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class WorkerThread;
class MainWindow : public QMainWindow
{
    Q_OBJECT

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

private:
    Ui::MainWindow *ui;

    WorkerThread* t;

private slots:
    void receiveData(float zhi);
};
#endif // MAINWINDOW_H

mainwindow.cpp 

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

#include <QApplication>

#include <QThread>
#include <QDebug>
#include <QTimer>

#include<workerthread.h>

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

    t=new WorkerThread;
    connect(t,&WorkerThread::sendData,this,&MainWindow::receiveData);
    t->start();
    //t->wait();  //线程执行完之前,会一直堵塞在这,一般用不上,因为用线程就是为了避免堵塞
}

void MainWindow::receiveData(float zhi){
    qDebug()<<"receive data from thread : "<<zhi;
}
MainWindow::~MainWindow()
{
    delete ui;
}


FR:徐海涛(hunklxu)


网站公告

今日签到

点亮在社区的每一天
去签到