- 新建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 "mylineedit.h"
#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);
}
#ifndef 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
#include "widget.h"
#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;
}
#include <QtGui/QApplication> #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(); }