Qt事件机制 五种级别的事件过滤

80、知道Qt事件机制有几种级别的事件过滤吗?能大致描述下吗?

根据对Qt事件机制的分析,我们可以得到5种级别的事件过滤,处理办法.以功能从弱到强,排列如下:

1 )重载特定事件处理函数.

最常见的事件处理办法就是重载象mousePressEvent), keyPressEvent(), paintEvent()这样的特定事件处理函数.

2 )重载event()函数.

通过重载event()函数,我们可以在事件被特定的事件处理函数处理之前(象keyPressEvent()处理它.比如,当我们想改变tab键的默认动作
时,一般要重载这个函数.在处理一些不常 见的事件(比如:L ayoutDirectionChange)时,evnet()也很有用,因为这些函数没有相应的特定事件处
理函数.当我们重载event()函数时,需要调用父类的event()函数来处理我们不需要处理或是不清楚如何处理的事件.

//void Ledit::keyPressEvent(QKeyEvent *event)
//{
// QString str=event->text();
// if(str.toLower() == "q")
// {
// //event->key() == Qt::Key_Q

// qDebug()<<"cin>>q";
// }
// else
// {
// QLineEdit::keyPressEvent(event);
// }
//}

//bool Ledit::event(QEvent e)
//{
// QKeyEvent
_event;
// if(e->type() == QEvent::KeyPress)
// _event=static_cast<QKeyEvent*>(e);
// else{
// //QLineEdit::event(e);
// return QLineEdit::event(e);
// }

// QString str=_event->text();
// if(str.toLower() == "q")
// {
// //event->key() == Qt::Key_Q

// qDebug()<<"event cin>>q";
// }
// else
// {
// QLineEdit::keyPressEvent(_event);
// }

// return QLineEdit::event(e);
//}

3)在Qt对象上安装事件过滤器.

安装事件过滤器有两个步骤: (假设要用A来监视过滤B的事件)

首先调用B的nstalEventFilter( const QOject *obj ),以A的指针作为参数.这样所有发往B的事件都将先由A的eventFilter()处理.

然后,A要重载QObject:eventFilter()函数,在eventilter()中书泻对事件进行处理的代码.

auto layout=ui->centralwidget->layout();
Ledit* lineedit=new Ledit(ui->centralwidget);
layout->addWidget(lineedit);

filterA=new MyEventFilter();
lineedit->installEventFilter(filterA);

4 )给QAppliction对象安装事件过滤器.

一旦我们给qApp(每 个程序中唯一的QApplic ation对象)装上过滤器,那么所有的事件在发往任何其他的过滤器时,都要先经过当前这个
eventFilter().在debug的时候这个办法就非常有用,也常常被用来处理失效了的widget的鼠标事件.通常这些事件会被QApplic aon:notif()
丢掉. (在Qplication:notify()中,是先调用qApp的过滤器,再对事件进行分析,以决定是否合并或丢弃)

QApplication a(argc, argv);
MainWindow w;

MyEventFilter* filter=new MyEventFilter();

a.installEventFilter(filter);

bool MyEventFilter::eventFilter(QObject *watched, QEvent *event)
{

if (event->type() == QEvent::KeyPress) {
        QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
        qDebug() <<watched->objectName()<< "Filtered key press:" << keyEvent->text();
        // 返回 false 允许事件继续传递给目标对象
        return false;
    }
    // 对于其他类型的事件,使用默认的事件处理
    return QObject::eventFilter(watched, event);

5)继承QApplication类 并重载ntify()函数.

Qt是用Qpplcation:notify()函数来分发事件的想要在任何事件过滤器查看任何事件之前先得到这些事件重载这个函数是唯一的办法. 通
常来说事件过滤器更好用一些, 因为不需要去继承QApplication类.而且可以给QApplication对象安装任意个数的事件。

重载 QApplication::notify() 方法可以让你在任何事件被分发到目标对象之前先捕获并处理这些事件
继承继承QApplication类,重写notify()
自定义的类代替QApplication,CustomApplication app(argc, argv);

posted on 2025-02-23 10:56  不败剑坤  阅读(283)  评论(0)    收藏  举报

导航