Qt: Defining a custom event type

Viewed 26195

I have created a custom event in my Qt application by subclassing QEvent.

class MyEvent : public QEvent
{
  public:
    MyEvent() : QEvent((QEvent::Type)2000)) {}
    ~MyEvent(){}
}

In order to check for this event, I use the following code in an event() method:

if (event->type() == (QEvent::Type)2000)
{
  ...
}

I would like to be able to define the custom event's Type somewhere in my application so that I don't need to cast the actual integer in my event methods. So in my event() methods I'd like to be able to do something like

if (event->type() == MyEventType)
{
  ...
}

Any thoughts how and where in the code I might do this?

3 Answers

If the event-type identifies your specific class, i'd put it there:

class MyEvent : public QEvent {
public:
    static const QEvent::Type myType = static_cast<QEvent::Type>(2000);
    // ...
};

// usage:
if(evt->type() == MyEvent::myType) {
    // ...
}
Related