其实就是和Qt::QueuedConnection时的信号槽一样,属于异步的。

1、新建QEvent子类

①、头文件

#ifndef MYEVENT_H

#define MYEVENT_H

#include <QString>

#include <QEvent>

class MyEvent : public QEvent

{

QString m_data;

public:

const static Type TYPE = static_cast<Type>(QEvent::User + 0xFF);

MyEvent(QString data = "");

QString data();

};

#endif // MYEVENT_H

②、cpp

#include "myevent.h"

MyEvent::MyEvent(QString data) : QEvent(TYPE)

{

m_data = data;

}

QString MyEvent::data()

{

return m_data;

}

2、在任何需要发送消息的地方

QApplication::postEvent(parent(), new MyEvent("Begin"));//必须在堆上建空间

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

{

QApplication::postEvent(parent(), new MyEvent(QString::number(i)));

msleep(1);

}

QApplication::postEvent(parent(), new MyEvent("End"));

3、在主界面中处理消息

bool MainWindow::event(QEvent *evt)

{

bool ret = true;

if( evt->type() == MyEvent::TYPE )

{

MyEvent* se = dynamic_cast<MyEvent*>(evt);

if( se != NULL )

{

ui->plainTextEdit->appendPlainText(se->data());

}

}

else

{

ret = QWidget::event(evt);

}

return ret;

}

05-11 20:35