Qt 线程与线程之间数据传递

有时候我们需要不同的线程之间进行数据的传送,使得数据合并,达到完成的数据,这里简单记录下线程之间的传递。基本思想通过槽函数也让线程1与线程2绑定发送数据与接受数据函数。

创建一个QT Widgets工程,添加两个线程类。OneThread,与  twoThread

onethread.h

#ifndef ONETHREAD_H
#define ONETHREAD_H

#include <QObject>
#include <QThread>

class OneThread : public QThread
{
    Q_OBJECT
public:
    OneThread();
    void send(int data);

signals:
     void sendData(int data);
public slots:

};

#endif // ONETHREAD_H

onethread.cpp

#include "onethread.h"

OneThread::OneThread()
{

}

void OneThread::send(int data)
{
    emit sendData(data);
}

twothread.h

#ifndef TWOTHREAD_H
#define TWOTHREAD_H

#include <QObject>
#include <QThread>
class twoThread : public QThread
{
    Q_OBJECT
public:
    twoThread();

    void getData(int getData);

signals:

public slots:
    
};

#endif // TWOTHREAD_H

twothread.cpp

#include "twothread.h"
#include <QDebug>
twoThread::twoThread()
{

}

void twoThread::getData(int getData)
{
    qDebug() << getData << endl;
}

 界面如下图:

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include "onethread.h"
#include "twothread.h"

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();
private slots:
    void on_pushButton_clicked();

private:
    OneThread *oneThd;
    twoThread *twoThd;
private:
    Ui::MainWindow *ui;
};

#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);
    oneThd = new OneThread();
    twoThd = new twoThread();
    connect(oneThd,&OneThread::sendData,twoThd,&twoThread::getData);

}

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

void MainWindow::on_pushButton_clicked()
{
    oneThd->send(12);
}

运行结果:

点击按钮后,线程2收到了数据。

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值