欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

Qt 中的事件和事件处理

最编程 2024-04-04 22:23:08
...

异步事件处理

  • 使用QApplication::postEvent()方法可以将事件异步地添加到事件队列中,供以后处理。
void postCustomEvent(MyWidget *target)
{
    QEvent *customEvent = new CustomEvent(); // 自定义事件类,继承自QEvent
    QApplication::postEvent(target, customEvent); // 异步发送事件
}

class MyWidget : public QWidget
{
    // ...
protected:
    bool event(QEvent *e) override
    {
        if (e->type() == CustomEvent::Type)
        {
            CustomEvent *customEvent = static_cast<CustomEvent*>(e);
            // 处理自定义事件...
            return true;
        }
        return QWidget::event(e);
    }
};

// 定义自定义事件
class CustomEvent : public QEvent
{
public:
    static const QEvent::Type Type;

    CustomEvent() : QEvent(Type) {}

    // ... 其他成员函数和数据 ...
};

别忘了在头文件中声明CustomEvent::Type

// CustomEvent.h
Q_DECLARE_EVENT_TYPE(CustomEvent::Type, "CustomEventType")

并在源文件中初始化:

// CustomEvent.cpp
const QEvent::Type CustomEvent::Type = QEvent::registerEventType();

推荐阅读