思路:在子线程中使用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();
}
输出