Custom QT Events
-
Hi guys,
I have a very simple subclass of QEvent:
#ifndef FFTEVENT_H #define FFTEVENT_H #include <eventdefs.h> #include <QDebug> class FFTEvent : public QEvent { public: FFTEvent(float val = 0.0f, float thresh = 50.0f); virtual float getValue(); virtual float getThreshold(); protected: float value; float threshold; }; #endif // FFTEVENT_H
My question is what is the best C++ approach to register this custom event class in a header so that I could pass the registered type to the constructor of the class?
#include "fftevent.h" FFTEvent::FFTEvent(float val, float thresh) : QEvent(FFTEventType), value(val), threshold(thresh) { qDebug() << "Request to create event object of type " << FFTEventType << " created event object of type " << type(); }
Using a static const variable results in different values being registered every time the header below is included:
#ifndef EVENTDEFS_H #define EVENTDEFS_H #include <QEvent> static const QEvent::Type FFTEventType = static_cast<QEvent::Type>(QEvent::registerEventType()); #endif // EVENTDEFS_H
I would use the QCustomEvent class but it doesn't seem to exist in QT 5.11 or 5.12.
Cheers!
-
@rtavakko
What is the point to set a global variable asstatic
in the header file?
Thestatic
in front of a global variable is different from the one in front of a class member variable.
If you only want it to be used from insideFFTEvent
, then put it in the cpp file.
If you may use it in other places:
option1. make it a publicstatic
member variable ofFFTEvent
in the header file and init it in the cpp file.
option2. declare it asextern
, notstatic
, in the header, and init it in the cpp file.
option3. put it in the cpp file, and create a publicstatic
member function ofFFTEvent
to return the value of it. -
@Bonnie Thanks for replying. My thought process was since QEvent takes a QEvent::Type as argument, then this means that it should be registered before in a global header which is what I'm trying to do. Having it in the class itself would work but is there a way to register events elsewhere?
-
Option 2 suggested above works best I think and is the cleanest solution. To sum it up:
Header file for event definition:
#ifndef EVENTDEFINITIONS_H #define EVENTDEFINITIONS_H #include <QEvent> extern const QEvent::Type TYPE_AUDIO; #endif // EVENTDEFINITIONS_H
Cpp file for the event definitions where it is initialized:
#include <eventdefinitions.h> const QEvent::Type TYPE_AUDIO = static_cast<QEvent::Type>(QEvent::registerEventType());
Event subclass:
#ifndef AUDIOEVENT_H #define AUDIOEVENT_H #include <eventdefinitions.h> #include <QDebug> class AudioEvent : public QEvent { public: explicit AudioEvent(); }; #endif // AUDIOEVENT_H
#include "audioevent.h" AudioEvent::AudioEvent() : QEvent(TYPE_AUDIO) { qDebug()<<QString("Creating custom event(%1)").arg(static_cast<int>(type())); }