标签:exe new sse private text use ret ESS end
MyPushButton.h:
#ifndef MYPUSHBUTTON_H #define MYPUSHBUTTON_H #include<QPushButton> #include<QEvent> #include<QMouseEvent> class MyPushButton : public QPushButton { public: MyPushButton(); MyPushButton(const QString& text,QWidget *parent=nullptr); bool event(QEvent *e); void mousePressEvent(QMouseEvent *e); }; #endif // MYPUSHBUTTON_H
MyPushButton.cpp:
#include "MyPushButton.h" #include<QWidget> #include<QDebug> MyPushButton::MyPushButton(const QString& text,QWidget *parent) :QPushButton(text,parent) { } bool MyPushButton::event(QEvent *e) { if(e->type()==QEvent::MouseButtonPress) { QMouseEvent *x=static_cast<QMouseEvent*>(e); mousePressEvent(x); //e->ignore(); //e->accept(); return false; //表示我不处理这个事件 //return true; //表示我处理了这个事件 } return QWidget::event(e); } void MyPushButton::mousePressEvent(QMouseEvent *e) { qDebug()<<"子类的事件执行"<<endl; } MyPushButton::MyPushButton() { }
Widget.h:
#ifndef WIDGET_H #define WIDGET_H #include <QWidget> #include "MyPushButton.h" class Widget : public QWidget { Q_OBJECT public: Widget(QWidget *parent = 0); ~Widget(); bool event(QEvent *e); void mousePressEvent(QMouseEvent *e); private: MyPushButton *mypushbutton; }; #endif // WIDGET_H
Widget.cpp:
#include "widget.h" #include<QDebug> Widget::Widget(QWidget *parent) : QWidget(parent) { mypushbutton=new MyPushButton("按钮",this); } bool Widget::event(QEvent *e) { return QWidget::event(e); } void Widget::mousePressEvent(QMouseEvent *e) { qDebug()<<"父类的事件执行"<<endl; } Widget::~Widget() { }
main.cpp:
#include "widget.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); Widget w; w.show(); return a.exec(); }
效果:
标签:exe new sse private text use ret ESS end
原文地址:https://www.cnblogs.com/SunShine-gzw/p/13270001.html