栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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 


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

}




转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/510134.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号