Events in Qt (3) - custom events


1. Custom event steps

Sometimes for development needs, we want to customize events to accomplish a certain purpose. The steps to implement a custom event are as follows:

  • Inherit QEvent.
  • Define the event type (the value is between QEvent::User and QEvent::MaxUser, it is recommended to use the registerEventType() function to automatically create a globally unique event type to prevent repetition)
  • Send events using sendEvent() or postEvent().
  • You need to override the QObject::event() method in your custom class to handle custom events.

2. Custom event class

The custom event class code is as follows:
header file

// -------------------------- 自定义事件 --------------------------------
class CustomerEvent : public QEvent
{
public:
    CustomerEvent(QString valueString = "");
    ~CustomerEvent();

    static Type eventType();
    QString getValueString(void);

private:
    static Type m_EventType;
    QString m_String;
};

Source File

QEvent::Type CustomerEvent::m_EventType = QEvent::None;

CustomerEvent::CustomerEvent(QString valueString) : QEvent(eventType())
{
    m_String = valueString;
}

CustomerEvent::~CustomerEvent()
{

}

QEvent::Type CustomerEvent::eventType()
{
    // 创建事件Type
    if (m_EventType == QEvent::None)
        m_EventType = (QEvent::Type)QEvent::registerEventType();

    return m_EventType;
}

QString CustomerEvent::getValueString(void)
{
    return m_String;
}

Here the CustomerEvent::eventType() function is used to create the type for the event.

3. Send events

There are two ways to send events, one is to use the sendEvent() function and the other is to use the postEvent() function.

(1) sendEvent method

The sendEvent() method is blocking, it sends an object event and returns after waiting for the received object to finish processing. The function prototype is as follows:
static bool QCoreApplication::sendEvent(QObject *receiver, QEvent *event);
Parameters: receiver is the object receiving the event, event is the passed event pointer
Return value: Returns true if the event is processed, otherwise returns false.
Description: This function needs to manually release the event memory.

(2) postEvent method

postEvent() is an asynchronous method that registers an event with a specified receiver in the event queue and returns. The function prototype is as follows:
static void QCoreApplication::postEvent(QObject *receiver, QEvent *event, int priority = Qt::NormalEventPriority);
Parameters: receiver is the object receiving the event, event is the passed event pointer, priority is the priority
Description : This function does not need to manually release the event memory, it is automatically released by the Qt framework.

An example of using PostEvent and SendEvent is as follows:
header file

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

protected:
    virtual bool event(QEvent *event) override;
};

A Widget is defined here, which will be used when the event() function is used to process custom events later.

Source File

Widget::Widget(QWidget *parent) :
    QWidget(parent)
{
    // 创建按钮并布局
    QPushButton *button = new QPushButton("CreateEvent", this);
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->addWidget(button);
    this->setGeometry(100, 100, 800, 600);

    // 建立连接, 发送信号
    QObject::connect(button, &QPushButton::clicked, [=](void)->void{
        // 使用PostEvent方式发送
        CustomerEvent *customerEvent = new CustomerEvent("PostCustomerEvent");
        QCoreApplication::postEvent(this, customerEvent);

        // 使用SendEvent方式发送
        CustomerEvent *sendCustomerEvent = new CustomerEvent("SendCustomerEvent");
        bool result = QCoreApplication::sendEvent(this, sendCustomerEvent);
        qDebug() << "The Dispose Result Is " << result;
        delete sendCustomerEvent;
    });
}

Widget::~Widget()
{

}

This creates a button that sends a custom event when the button is pressed.

4. Event handling

Handle custom events by overriding QObject::event(). code show as below:

bool Widget::event(QEvent *event)
{
    if (event->type() == CustomerEvent::eventType())
    {
        CustomerEvent *customerEvent = dynamic_cast<CustomerEvent*>(event);
        qDebug() << customerEvent->getValueString();
        return true;
    }
    return QWidget::event(event);
}

The function returns true to indicate that the event has been handled, otherwise it returns false.

The running result of the overall program is:
“SendCustomerEvent”
The Dispose Result Is true
“PostCustomerEvent”
can be seen, the function first processes the events of the sendEvent() function, and then distributes it to the current object for processing when the event loop runs.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325567554&siteId=291194637