Qt多线程之线程之间的传递数据

.hpp

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include 
#include
#include
static QVector<int>myArray;
static QVector<int>myAnotherArray;
namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

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

private slots:
    void on_pushButton_clicked();
    void updateSlot(int _number);

    void on_pushButton_2_clicked();

private:
    Ui::MainWindow *ui;
    int number;
};

class MyThread:public QThread
{
    Q_OBJECT
public:
    MyThread(){}
    void run();
    void getNumber(int & number);
signals:
    void updateSignal(int num);
private:
    int myNumber;

};

#endif // MAINWINDOW_H

.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    MyThread * thread = new MyThread();
    thread->start();
    connect(thread,SIGNAL(updateSignal(int)),this,SLOT(updateSlot(int)));

}

MainWindow::~MainWindow()
{
    delete ui;

}

void MainWindow::on_pushButton_clicked()
{
    QTime time;
    time= QTime::currentTime();
    qsrand(time.msec()+time.second()*1000);
    int n = qrand() % 50; //产生50以内的随机数
    myArray.push_back(n);


}

void MainWindow::on_pushButton_2_clicked()
{
//    if(myAnotherArray.size() >0)
//    {
//        int front = myAnotherArray.front();
//        ui->plainTextEdit->appendPlainText(QString::number(front));
//        myAnotherArray.pop_front();
//    }

}

void MainWindow::updateSlot(int _number){

    ui->plainTextEdit->appendPlainText(QString::number(_number));

}

void MyThread::getNumber(int & number){

    myNumber = number;
}

void MyThread::run(){

    while(!isInterruptionRequested())
    {
        if(myArray.size() > 0)
        {

            myNumber = myArray.front();
            myAnotherArray.push_back(myNumber);
            qDebug()<<myNumber;
            myArray.pop_front();

            emit updateSignal(myNumber);
            msleep(50);
        }
    }

}

main.cpp

#include "mainwindow.h"
#include 

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

    return a.exec();
}

运行结果
Qt多线程之线程之间的传递数据_第1张图片
线程中生成的随机数
Qt多线程之线程之间的传递数据_第2张图片

你可能感兴趣的:(多线程实战,多线程,thread,qt,c++,random)