Is there a cleaner way to register Qt custom events?

大城市里の小女人 提交于 2019-12-03 14:56:04

That's what templates are for. They can be used with constant integral parameters, which need to be known at compile time too:

enum EventNames { UpdateEvent,... }

template<EventNames E>
class MyEvent : public QEvent
{
public:
    MyEvent() : QEvent(registeredType())
    {
    }

    static QEvent::Type eventType;

private:
    static QEvent::Type registeredType();
}

The common code lokes like this:

template<EventNames E>
QEvent::Type MyEvent<E>::registeredType()
{
    if (eventType == QEvent::None)
    {
        int generatedType = QEvent::registerEventType();
        eventType = static_cast<QEvent::Type>(generatedType);
    }
    return eventType;
}

Static initialization (beware!) looks like this:

QEvent::Type MyEvent<UpdateEvent>::eventType = QEvent::None;

The code specific for each event type can be implemented as template specialization then.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!