//widget.h #ifndef WIDGET_H #define WIDGET_H #include <QWidget> #include"mylineedit.h" #include <QKeyEvent> namespace Ui { class Widget; } class Widget : public QWidget { Q_OBJECT public: explicit Widget(QWidget *parent = 0); ~Widget(); private: Ui::Widget *ui; private: myLineEdit * myEdit; protected: void keyPressEvent(QKeyEvent * event); public: bool eventFilter(QObject *watched, QEvent *event); //定义事件过滤器 }; #endif // WIDGET_H
//widget.cpp #include "widget.h" #include "ui_widget.h" #include "mylineedit.h" #include<QDebug> Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) { ui->setupUi(this); myEdit = new myLineEdit(this); myEdit->move(100,100); myEdit->installEventFilter(this);//给myEdit安装事件过滤器 } Widget::~Widget() { delete ui; } void Widget:: keyPressEvent(QKeyEvent * event) { qDebug()<<tr("父窗口widget的键盘按下事件的处理函数被调用"); } bool Widget::eventFilter(QObject *watched, QEvent *event) { if(watched == myEdit) if(event->type()==QEvent::KeyPress) qDebug()<<tr("父窗口widget的事件过滤器被调用"); return QWidget::eventFilter(watched,event); //最后返回QWidget类默认的事件过滤器eventFilter()的执行结果 }
//myLineEdit.h #ifndef MYLINEEDIT_H #define MYLINEEDIT_H #include <QLineEdit> class myLineEdit : public QLineEdit { Q_OBJECT public: explicit myLineEdit(QWidget * widget); protected: void keyPressEvent(QKeyEvent * event); public: bool event(QEvent *event);//重写事件函数,在事件传给事件处理函数之前,捕获事件 }; #endif // MYLINEEDIT_H
//MyLineEdit.cpp #include "mylineedit.h" #include <QDebug> #include <QKeyEvent> myLineEdit::myLineEdit(QWidget * widget):QLineEdit(widget) { } void myLineEdit::keyPressEvent(QKeyEvent *event) { qDebug()<<tr("输入框的键盘按下事件处理函数"); QLineEdit::keyPressEvent(event); event->ignore();//忽略该事件,交给父窗口处理 } bool myLineEdit::event(QEvent *event) { if(event->type() == QEvent::KeyPress) qDebug()<<tr("输入框自己的event函数,在调用事件处理函数之前,捕获事件"); return QLineEdit::event(event); //调用QLineEdit的默认event 函数,不然MyLineEdit界面显示会发生异常 //该函数一般返回父类的event()函数的操作结果 }
//main.cpp #include "widget.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); Widget w; w.show(); return a.exec(); }