QT 增加自定义Event类型,使用postEvent前创建对象注意事项

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);
    }

}




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值