QT 事件传递

QEvent的 accept()函数 和 ignore()函数:

accept():本组件处理该事件,这个事件就不会被继续传播给其父组件

ignore():本组件不想要处理这个事件。这个事件被继续传播给其父组件

注意:这里事件的传播是在组件层次上面的,而不是依靠类继承机制。

 

那么,如何使用该对象的父类的处理函数呢:直接调用即可。

 

看实例:

我们自定义一个button类:

custombutton.h

#ifndef CUSTOMBUTTON_H
#define CUSTOMBUTTON_H

#include <QObject>
#include <QPushButton>

class CustomButton : public QPushButton
{
    Q_OBJECT
        using QPushButton::QPushButton;
protected:
    void mousePressEvent(QMouseEvent *event) override;
};




#endif // CUSTOMBUTTON_H

custombutton.cpp

#include "custombutton.h"

#include <QMouseEvent>
#include <QDebug>

void CustomButton::mousePressEvent(QMouseEvent *event)
{
     event->ignore(); //accept()和ignore() 表示是否将事件传递出去,是传递给父组件,而不是父对象

    qDebug() << "this:" << this << ", CustomButton::mousePressEvent";
}

再定义一个子类:

custombutton_sun.h

#ifndef CUSTOMBUTTON_SUN_H
#define CUSTOMBUTTON_SUN_H

#include <QObject>

#include <QPushButton>
#include "CustomButton.h"

class CustomButton_Sun : public CustomButton
{
    Q_OBJECT
        using CustomButton::CustomButton;
protected:
    void mousePressEvent(QMouseEvent *event) override;

};
#endif // CUSTOMBUTTON_SUN_H

custombutton_sun.cpp

#include "custombutton_sun.h"

#include <QMouseEvent>
#include <QDebug>



void CustomButton_Sun::mousePressEvent(QMouseEvent *event)
{
    qDebug() << "this:" << this << ", CustomButton_Sun::mousePressEvent";

    CustomButton::mousePressEvent(event);  //调用本组件的父类函数
}

 

我们在一个 CustomButton_Sun对象上面放一个CustomButton对象;

如图:

image

点击CustomButton对象,打印结果:

this: CustomButton(0x4bd160, name="customButton") , CustomButton::mousePressEvent
this: CustomButton_Sun(0x4bcde0, name="customButton_Sun") , CustomButton_Sun::mousePressEvent
this: CustomButton_Sun(0x4bcde0, name="customButton_Sun") , CustomButton::mousePressEvent

转载于:https://www.cnblogs.com/fluteary/p/9232711.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值