- 新建Qt Gui项目,基类选择QWidget
- 添加新文件,基于C++类,类名MyLineEdit
- mylineedit.h中代码:
- #ifndef MYLINEEDIT_H
#define MYLINEEDIT_H
#include <QLineEdit>
class MyLineEdit : public QLineEdit
{
Q_OBJECT
public:
explicit MyLineEdit(QWidget *parent = 0);
bool event(QEvent *event);
signals:
public slots:
protected:
void keyPressEvent(QKeyEvent *event);
};
//void MyLineEdit::keyPressEvent()
#endif // MYLINEEDIT_H - mylineedit.cpp中代码:
#include <QDebug>
#include <QKeyEvent>
MyLineEdit::MyLineEdit(QWidget *parent) :
QLineEdit(parent)
{
}
void MyLineEdit::keyPressEvent(QKeyEvent *event)
{
//qDebug()<<tr("MyLineEdit键盘按下事件");
QLineEdit::keyPressEvent(event);
event->ignore();
}
bool MyLineEdit::event(QEvent *event)
{
if(event->type()==QEvent::KeyPress)
qDebug()<<tr("MyLineEdit的event函数");
return QLineEdit::event(event);
}
- widget.h中代码:
#define WIDGET_H
#include <QWidget>
class MyLineEdit;
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
bool eventFilter(QObject *obj,QEvent *event);
protected:
void keyPressEvent(QKeyEvent *event);
private:
Ui::Widget *ui;
MyLineEdit *lineEdit;
};
#endif // WIDGET_H
- widget.cpp中代码:
#include "ui_widget.h"
#include "mylineedit.h"
#include <QKeyEvent>
#include <QDebug>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
lineEdit=new MyLineEdit(this);
lineEdit->move(100,100);
lineEdit->installEventFilter(this);//在widget上为lineEdit安装事件过滤器
}
void Widget::keyPressEvent(QKeyEvent *event)
{
qDebug()<<tr("Widget键盘按下事件");
}
bool Widget::eventFilter(QObject *obj,QEvent *event)
{
if(obj==lineEdit)
{
if(event->type()==QEvent::KeyPress)
qDebug()<<tr("widget的事件过滤器");
}
return QWidget::eventFilter(obj,event);
}
Widget::~Widget()
{
delete ui;
}
- main.cpp中代码:
#include "widget.h"
#include <QTextCodec>
int main(int argc, char *argv[])
{
QTextCodec::setCodecForTr(QTextCodec::codecForLocale());
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}