Qt5线程之间通信的小例子

时间:2022-02-13 23:15:16

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include<QString>
namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
Q_OBJECT

public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
public slots:
void hasRead(QString);
private:
Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include"myreader.h"
#include<qthread.h>
#include<QDebug>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
qDebug()<<"Main Thread`s id:"<<this->thread()->currentThreadId();
//============
MyReader * reader=new MyReader();
QThread * t=new QThread();
reader->moveToThread(t);
//|注意新线程需要开启 start 否则不能使用!!
t->start();
QObject::connect(this->ui->pushButton,SIGNAL(clicked()),reader,SLOT(reading()));
QObject::connect(reader,SIGNAL(hasread(QString)),this,SLOT(hasRead(QString)));
}

MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::hasRead(QString s)
{
qDebug()<<"MainWindow::hasRead`s Thread id:"<<this->thread()->currentThreadId();
this->ui->textBrowser->append(s);
}
myreader.h

#ifndef MYREADER_H
#define MYREADER_H
#include<QObject>
#include<QString>
class MyReader:public QObject
{
Q_OBJECT
public:
MyReader();
~MyReader();
signals:
void hasread(QString);
public slots:
void reading();
};

#endif // MYREADER_H
myreader.cpp

#include "myreader.h"
#include<QDebug>
#include<qthread.h>
#include<QFile>
MyReader::MyReader()
{

}

MyReader::~MyReader()
{

}
void MyReader::reading()
{
qDebug()<<"MyReader`s Thread id :"<<this->thread()->currentThreadId();
QFile f("E:/1.txt");
f.open(QIODevice::ReadOnly);
QString data=f.readAll();
emit hasread(data);
}
main.cpp

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();

return a.exec();
}
运行结果:

Qt5线程之间通信的小例子

qDebug()输出结果:

Main Thread`s id: 0x1d3c
MyReader`s Thread id : 0x2260
MainWindow::hasRead`s Thread id: 0x1d3c
MyReader`s Thread id : 0x2260
MainWindow::hasRead`s Thread id: 0x1d3c

线程之间只能采用 信号、槽的 方式进行通信~