Search code examples
qtqevent

Qt. Declare custom QEvent type ONCE


I have a .h file with such code:

const QEvent::Type MyOnEventType =
           QEvent::Type(QEvent::registerEventType( QEvent::User + 500 ) );

This header uses twice in application. I found a problem that in different places MyOnEventType have different integer value. If make a break point on that code above, debugger stops 9 times.

Please help how to declare custom QEvent type ONCE


Solution

  • I'm not 100% sure I'm understanding your question, but it sounds like you need to separate the declaration and the implementation. Something like:

    my_event.h

    class MyEvent : public QEvent {
     public:
      static const QEvent::Type MyEventType;
      // etc. 
    };
    

    my_event.cpp

    #include "my_event.h"
    
    const QEvent::Type MyEvent::MyEventType = 
            static_cast<QEvent::Type>(QEvent::registerEventType());
    
    // etc.