프로그래밍/Qt

Thread 이벤트 Gui 폼에서 받기

Dev-Drake 2019. 6. 11. 14:12
반응형

// mainwindow.cpp

#include "mainwindow.h"

#include "ui_mainwindow.h"

 

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)

{

    ui->setupUi(this);

 

    mThread = new MyThread(this);

 

    connect(mThread, SIGNAL(NumberChanged(int)), this, SLOT(onNumberChanged(int)));

}

 

MainWindow::~MainWindow()

{

    delete ui;

}

 

void MainWindow::onNumberChanged(int Number)

{

    ui->LblNumber->setText(QString::number(Number));

}

 

void MainWindow::on_BtnStart_clicked()

{

    mThread->start();

}

 

void MainWindow::on_BtnStop_clicked()

{

    mThread->Stop = true;

}

 

// mainwindow.h

#ifndef MAINWINDOW_H

#define MAINWINDOW_H

 

#include <QMainWindow>

#include "mythread.h"

 

namespace Ui {

class MainWindow;

}

 

class MainWindow : public QMainWindow

{

    Q_OBJECT

    

public:

    explicit MainWindow(QWidget *parent = 0);

    ~MainWindow();

    

private:

    Ui::MainWindow *ui;

    MyThread *mThread;

 

public slots:

    void onNumberChanged(int);

 

private slots:

    void on_BtnStart_clicked();

    void on_BtnStop_clicked();

};

 

#endif // MAINWINDOW_H

 

 

// mythread.cpp

#include "mythread.h"

 

MyThread::MyThread(QObject *parent) : QThread(parent)

{

    Stop = false;

}

 

void MyThread::run()

{

    for(int i = 0; i < 10000; i ++) {

        m_Mutex.lock();

        if(Stop)    break;

        m_Mutex.unlock();

 

        // sleep(1);

        this->msleep(100);

 

        emit NumberChanged(i);

    }

}

 

// mythread.h

#ifndef MYTHREAD_H

#define MYTHREAD_H

 

#include <QThread>

#include <QMutex>

 

class MyThread : public QThread

{

    Q_OBJECT

 

private:

    QMutex  m_Mutex;

 

public:

    explicit MyThread(QObject *parent = 0);

    void run();

    bool Stop;

 

signals:

    void NumberChanged(int);

    

public slots:

    

};

 

#endif // MYTHREAD_H

 

반응형