1. 程式人生 > >QT通過執行緒將資料傳遞給主函式進行顯示

QT通過執行緒將資料傳遞給主函式進行顯示

根據別人的程式碼,自己重新寫一次加深印象。

標頭檔案mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QThread>
#include <QPushButton>
#include <QLabel>
#include <QVBoxLayout>
#include <QHBoxLayout>

class Thread : public QThread
{
    Q_OBJECT
public:
    Thread(QObject *parent=0);
    ~Thread();
private:
    int number;
protected:
    void run();
signals:
    void UpdateSignal(int num);
public slots:
    void ResetSlot();
};

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = 0);
    ~MainWindow();
    QLabel *showNum;
    QPushButton *startButton;
    QPushButton *stopButton;
    QPushButton *resetButton;
    Thread *myThread;
    int number;
signals:
    void ResetSignal();
public slots:
    void ClearSlot();
    void StartSlot();
    void StopSlot();
    void UpdateSlot(int num);
};

#endif // MAINWINDOW_H

cpp檔案main.cpp
#include "mainwindow.h"
#include <QApplication>

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

    return a.exec();
}
cpp檔案mainwindow.cpp
#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    setWindowTitle(tr("test event"));

    myThread = new Thread;
    showNum = new QLabel;
    startButton = new QPushButton(tr("start"));
    stopButton = new QPushButton(tr("stop"));
    resetButton = new QPushButton(tr("reset"));

    //連線各自訊號糟
    connect(stopButton, SIGNAL(clicked()), this, SLOT(StopSlot()));
    connect(startButton, SIGNAL(clicked()), this, SLOT(StartSlot()));
    connect(resetButton, SIGNAL(clicked()), this, SLOT(ClearSlot()));
    connect(myThread, SIGNAL(UpdateSignal(int)), this, SLOT(UpdateSlot(int)));
    connect(this, SIGNAL(ResetSignal()), myThread, SLOT(ResetSlot()));


//    myThread->start();

    QVBoxLayout *vbox = new QVBoxLayout;

    vbox->addWidget(showNum);
    vbox->addWidget(startButton);
    vbox->addWidget(stopButton);
    vbox->addWidget(resetButton);

    QWidget *centerWindow = new QWidget(this); // 使用者在mainwindow類中新增自定義的控制元件和佈局
    this->setCentralWidget(centerWindow);
    centerWindow->setLayout(vbox);
    centerWindow->setMinimumSize( 100, 120 );
}

void MainWindow::StartSlot()
{
    myThread->start();
}

void MainWindow::StopSlot()
{
    myThread->terminate();
}

void MainWindow::UpdateSlot(int num)
{
    showNum->setText(QString::number(num));
}

void MainWindow::ClearSlot()
{
    emit ResetSignal();
}

MainWindow::~MainWindow()
{

}

Thread::Thread(QObject *parent)
{
    number = 0;
}

Thread::~Thread()
{
}

void Thread::run()
{
    while(1)
    {
        //開啟一個死迴圈,讓number每秒自增1,並通過傳送UpdateSignal訊號通知主介面更新
        emit UpdateSignal(number);
        number++;
        sleep(1);
    }
}

void Thread::ResetSlot()
{
    number = 0;
    emit UpdateSignal(number);
}