首页 > 其他 > 详细

QT 事件过滤器 eventFilter

时间:2014-02-24 19:01:27      阅读:376      评论:0      收藏:0      [点我收藏+]

在监测的代码里执行需要的行为. 这可以用event Filter来达到. 设置一个event filter有两个步骤:
1. 在目标对象上调用installEventFilter(),将监测对象注册到目标对象上.
2. 在监测对象的eventFilter()方法里处理目标对象的事件.

在ctor里注册监测对象是一个好地方:
CustomerInfoDialog::CustomerInfoDialog(QWidget *parent) :QDialog(parent)
{
    ...
    firstNameEdit->installEventFilter(this);
    lastNameEdit->installEventFilter(this);
    cityEdit->installEventFilter(this);
    phoneNumberEdit->installEventFilter(this);
 }

一 旦event Filter注册了, 发送到firstNameEdit, lastNameEdit, cityEdit和phoneNumberEdit的事件在被发送到原来的目的地之前, 会先发到CustomerInfoDialog的eventFilter()函数.

这是接收这些事件的eventFilter()函数:
bool CustomerInfoDialog::eventFilter(QObject *target, QEvent *event)
{
    if (target == firstnameEdit || target == lastNameEdit
        || target == cityEdit || target == phoneNumberEdit)
    {
        if(event->type() == QEvent::KeyPress)
        {
            QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
            if (keyEvent->key() == Qt::Key_Space)
            {
                focusNextChild();
                return true;
            }
        }
    }
    return QDialog::eventFilter(target, event);
}

QT 事件过滤器 eventFilter

原文:http://www.cnblogs.com/wiessharling/p/3562348.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!