1. 程式人生 > 其它 >多執行緒與介面元件通訊

多執行緒與介面元件通訊

技術標籤:Qtqt

思路:在子執行緒中使用postEvent()傳送自定義的事件類物件,在主執行緒中更改介面狀態

//stringEvent.h  自定義事件類

#ifndef STRINGEVENT_H
#define STRINGEVENT_H

#include <QEvent>
#include <QString>

class stringEvent : public QEvent
{
private:
    QString m_data;
public:
    const static Type TYPE = static_cast<Type>(QEvent::User + 0XFF);    //自定義事件型別
    explicit stringEvent(QString data="");
    QString data();
};

#endif // STRINGEVENT_H



//stringEvent.cpp

#include "stringevent.h"

stringEvent::stringEvent(QString data) : QEvent(TYPE)
{
    m_data = data;
}

QString stringEvent::data()
{
    return m_data;
}

在Widget類中重寫event()函式,用來捕獲postEvent()傳送的事件

//updateui.h

#ifndef UPDATEUI_H
#define UPDATEUI_H

#include <QThread>
#include <QString>
#include <stringevent.h>


class UpdateUI : public QThread
{
    Q_OBJECT
private:
    void run();
public:
    explicit UpdateUI(QObject *parent = nullptr);

signals:
    void updateUISignal(QString text);

public slots:
};

#endif // UPDATEUI_H


//updateui.cpp

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

UpdateUI::UpdateUI(QObject *parent) : QThread(parent)
{

}

每隔1s傳送一個事件類物件
void UpdateUI::run()
{
    QApplication::postEvent(parent(), new stringEvent("begin"));

    for(int i=0; i<10; i++)
    {
        QApplication::postEvent(parent(), new stringEvent(QString::number(i)));

        sleep(1);
    }

    QApplication::postEvent(parent(), new stringEvent("end"));

    quit();
}
//widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <updateui.h>
#include <QPlainTextEdit>

class Widget : public QWidget
{
    Q_OBJECT

private:
    UpdateUI m_uiThread;
    QPlainTextEdit m_textEdit;
public:
    Widget(QWidget *parent = 0);
    bool event(QEvent *event);
    ~Widget();
};

#endif // WIDGET_H


//widget.cpp

#include "widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    m_textEdit.setParent(this);
    m_textEdit.resize(200, 200);

    m_uiThread.setParent(this);
    m_uiThread.start();
}

Widget::~Widget()
{
    m_uiThread.wait();
}

bool Widget::event(QEvent *event)
{
    if(event->type() == stringEvent::TYPE)
    {
        stringEvent* t = dynamic_cast<stringEvent*>(event);

        m_textEdit.appendPlainText(t->data());
    }
    else
    {
        return QWidget::event(event);
    }

    return true;
}

//main.cpp

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

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

    return a.exec();
}

輸出