Qt——发送自定义事件(下)

1.Qt可以自定义新的事件类

  • 自定义的事件类必须继承自QEvent
  • 自定义的事件类必须拥有全局唯一的Type值
  • 程序中必须提供处理自定义事件对象的方法

2.Qt中事件的Type值

  • 每个事件类都拥有全局唯一的Type值
  • 自定义事件类的Type值也需要自定义
  • 自定义事件类使用QEvent::User之后的值作为Type值
  • 程序中保证QEvent::User+VALUE全局唯一即可

3.处理自定义事件对象的方法

  • 将事件过滤器安装到目标对象:在eventFilter()函数中编写自定义事件的处理逻辑
  • 在目标对象的类中重写事件处理函数:在event()函数中编写自定义事件的处理逻辑

StringEvent.h

复制代码
#ifndef STRINGEVENT_H
#define STRINGEVENT_H

#include <QEvent>
#include <QObject>
#include <QString>

class StringEvent : public QEvent
{
    QString m_data;

public:
    const static Type TYPE = static_cast<Type>(QEvent::User + 0xFF);

    explicit StringEvent(QString data);
    QString data();
};

#endif // STRINGEVENT_H

StringEvent.cpp

复制代码
#include "StringEvent.h"
StringEvent::StringEvent(QString data) : QEvent(TYPE)
{
    m_data = data;
}
QString StringEvent::data()
{
    return m_data;
}

Widget.h

复制代码
#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QLineEdit>

class Widget : public QWidget
{
    Q_OBJECT
    QLineEdit m_edit;

public:
    explicit Widget(QWidget *parent = nullptr);
    bool event(QEvent* evt);
    bool eventFilter(QObject* obj, QEvent* evt);
    ~Widget() override;
};
#endif // WIDGET_H

Widget.cpp

复制代码
#include "Widget.h"
#include "StringEvent.h"
#include <QDebug>
#include <QApplication>

Widget::Widget(QWidget *parent) : QWidget(parent), m_edit(this)
{
    m_edit.installEventFilter(this);
}
bool Widget::event(QEvent* evt)
{
    if( evt->type() == QEvent::MouseButtonDblClick )
    {
        qDebug() << "event: Before sendEvent";

        StringEvent e("Hello World");
        QApplication::sendEvent(&m_edit, &e);
        qDebug() << "event: After sendEvent";
    }
    return QWidget::event(evt);
}
bool Widget::eventFilter(QObject* obj, QEvent* evt)
{
    if( (obj == &m_edit) && (evt->type() == StringEvent::TYPE) )
    {
        StringEvent* se = dynamic_cast<StringEvent*>(evt);
        qDebug() << "Receive: " << se->data();
        m_edit.insert(se->data());
        return true;
    }
    return QWidget::eventFilter(obj, evt);
}
Widget::~Widget() = default;

当双击widget时,运行结果:

并且可以将Hello World填充到lineEdit中

相关推荐
无限的鲜花12 小时前
反射(原创推荐)
java·开发语言
yongche_shi12 小时前
ragas官方文档中文版(五十)
开发语言·python·ai·ragas·如何评估和改进 rag 应用
一路向北he12 小时前
字节钢铁军团--“提供情境,而非控制”
java·开发语言·前端
AI行业学习14 小时前
Notepad++ 官方下载 + 完整安装 + 全套优化配置(2026最新)
开发语言·人工智能·python·前端框架·html·notepad++
大圣编程15 小时前
Python中continue语句的用法是什么?
开发语言·前端·python
upgrador15 小时前
基础知识:C++ STL构造函数的左闭右开惯例及其实现原理
开发语言·c++
yoothey16 小时前
报废审批流规则引擎设计——责任链模式完整实现
linux·开发语言·bash
尘中远16 小时前
【Qwt 7.0 系列】坐标轴与刻度系统 —— 刻度引擎、网格、图例与刻度朝内
qt·数据可视化·qcustomplot·qwt·工业软件·科学绘图
geovindu16 小时前
python: Functional Options Pattern
开发语言·后端·python·设计模式·惯用法模式·函数式选项模式
wuyk55516 小时前
24. C 语言模块化:不是拆几个.c 文件那么简单
c语言·开发语言·stm32·单片机