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

猜你喜欢

转载自www.cnblogs.com/fluteary/p/9232711.html