Qt__自定义事件

Posted narjaja

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Qt__自定义事件相关的知识,希望对你有一定的参考价值。

#include <QApplication>
#include <QEvent>
#include <QObject>
#include <QDebug>

const QEvent::Type MyEventType = (QEvent::Type)QEvent::registerEventType(QEvent::User+100);

class MyEvent: public QEvent
{
public:
    MyEvent(Type MyEventType):QEvent(MyEventType){}
};

class MyObject: public QObject
{
public:
    void MyEventHandler(QEvent *event);
    bool event(QEvent *event);
};

void MyObject::MyEventHandler(QEvent *event)
{
    qDebug()<<"The event is being handled!";
    event->accept();
}

bool MyObject::event(QEvent *event)
{
    if(event->type() == MyEventType)
    {
        qDebug()<<"event() is dispathing MyEvent";
        MyEventHandler(event);
        if((MyEvent*)event->isAccepted())
        {
            qDebug()<<"The event has been handled!";
            return true;
        }
    }
    return QObject::event(event);
}


int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    MyObject mywindow;
    MyEvent myEvent(MyEventType);
    a.sendEvent(&mywindow,&myEvent);
    return a.exec();
}

运行结果

以上是关于Qt__自定义事件的主要内容,如果未能解决你的问题,请参考以下文章

qt 自定义折线图

Qt:定义自定义事件类型

如何从 Qt 对话框中获取自定义信号

有没有更简洁的方法来注册 Qt 自定义事件?

4.1.6EventHandler自定义事件参数类

qt自定义槽函数不起作用