you should allocate the event on the heap(堆), not as a local variable:
TagReadEvent * event = new TagReadEvent;
It will be destroyed and deallocated by the event loop running in the destination thread.
From the docs: QCoreApplication::postEvent:
Adds the event event, with the object receiver as the receiver of the event, to an event queue and returns immediately.
The event must be allocated on the heap since the post event queue will take ownership of the event and delete it once it has been posted. It is not safe to access the event after it has been posted. (emphasis mine)
假设有一个类CTest,现定义两个CTest的对象
CTest t1;
CTest *t2 = new CTest();
1.本质不同
t1为类对象。
t2为类对象的指针。
2.作用域不同
t1作用域限制在定义类对象的方法中,当方法结束时,类对象也会被系统释放,不需要手工释放,安全不会造内存泄露。
t2作用域为全局,当程序结束时,需要使用delete进行手工释放,系统不会自动释放,如果忘记释放,容易造成内存泄露
3.内存中存放地址不同
t1存放在栈中。
t2存放在堆中。
即
直接声明的为栈变量,由系统自动分配内存和释放,为局部变量,在退出本函数以后,自动释放。
new出来的需要是指针变量。new出来的变量存储在堆上,在退出本函数以后,如果,没有delete,将发生内存泄漏。可以转化成全局变量。
代码:
MyEvent.h
#ifndef MYEVENT_H
#define MYEVENT_H
#include <qcoreevent.h>
class MyEvent : public QEvent
{
public:
MyEvent();
MyEvent(int x, int y, int z);
static const Type type = MyEventType;
int x;
int y;
int z;
};
#endif // MYEVENT_H
MyEvent.cpp
#include<MyEvent.h>
MyEvent::MyEvent():QEvent(QEvent::Type(type))
{
}
MyEvent::MyEvent(int x,int y,int z) :QEvent(QEvent::Type(type))
{
this->x = x;
this->y = y;
this->z = z;
}
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "MyEvent.h"
#include "windows.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
thread = new MyThread(thread);
//连接信号 槽
connect(ui->pushButton,SIGNAL(clicked()), this, SLOT(ClickButton()));
connect(thread, SIGNAL(Send2UI(int)), this, SLOT(ChangeText(int)));
//启动线程,处理数据
thread->start();
}
int i = 1;
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::ChangeText(int x)
{
ui->label->setText(QString::number(x));
i++;
}
bool MainWindow::event(QEvent *event)
{
switch (event->type()) {
case QEvent::MyEventType:
Sleep(1000);
ChangeText(((MyEvent *)event)->x);
return true;
break;
default:
return QWidget::event(event);
break;
}
// return QWidget::event(event);
}
void MainWindow::ClickButton()
{
for(int i = 11;i<10001;i++)
{
MyEvent *event = new MyEvent(i,2,3);
QApplication::postEvent(this, event);
}
}