Qt中事件的传递

  • 新建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();
}


转载于:https://my.oschina.net/u/574191/blog/128047

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值