有时候我们需要不同的线程之间进行数据的传送,使得数据合并,达到完成的数据,这里简单记录下线程之间的传递。基本思想通过槽函数也让线程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收到了数据。