Qt: Defining a custom event type

后端 未结 3 1197
粉色の甜心
粉色の甜心 2020-12-29 07:53

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

class MyEvent : public QEvent
{
  public:
    MyEvent() : QEvent((QEvent::Type)20         


        
3条回答
  •  情话喂你
    2020-12-29 08:13

    The idiomatic way of dealing with such problems is to create a template wrapper class, leveraging CRTP. For each custom event type, such template represents a new type, thus a separate staticType() member exists for each type, returning its unique registered type.

    Below I give three ways of identifying types:

    1. By staticType() -- this is only useful within an invocation of the application, and is the type to be used with QEvent. The values are not guaranteed to stay the same between invocations of an application. They do not belong in durable storage, like in a log.

    2. By localDurableType() -- those will persist between invocations and between recompilations with the same compiler. It saves manual definition of durableType() method when defining complex events.

    3. By durableType() -- those are truly cross platform and will be the same unless you change the event class names within your code. You have to manually define durableType() if you're not using the NEW_QEVENT macro.

    Both localDurableType() and durableType() differ betwen Qt 4 and 5 due to changes to qHash.

    You use the header in either of two ways:

    #include "EventWrapper.h"
    
    class MyComplexEvent : public EventWrapper {
       // An event with custom data members
       static int durableType() { return qHash("MyEvent"); }
       ...
    };
    
    NEW_QEVENT(MySimpleEvent) // A simple event carrying no data but its type.
    

    EventWrapper.h

    #ifndef EVENTWRAPPER_H
    #define EVENTWRAPPER_H
    
    #include 
    #include 
    
    template  class EventWrapper : public QEvent {
    public:
       EventWrapper() : QEvent(staticType())) {}
       static QEvent::Type staticType() {
          static int type = QEvent::registerEventType();
          return static_cast(type);
       }
       static int localDurableType() {
          static int type = qHash(typeid(T).name());
          return type;
       }
    };
    
    #define NEW_QEVENT(Name) \
       class Name : public EventWrapper< Name > \
       { static int durableType() { \
           static int durable = qHash(#Name); return durable; \
         } };
    
    #endif // EVENTWRAPPER_H
    

提交回复
热议问题