Qt中事件的传递

原创
2013/05/06 22:58
阅读数 905
  • 新建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);
}

  • widget.h中代码:
#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

  • widget.cpp中代码:
#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;
}


  • main.cpp中代码:
#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();
}


展开阅读全文
打赏
0
3 收藏
分享
加载中
更多评论
打赏
0 评论
3 收藏
0
分享
返回顶部
顶部