Chinaunix首页 | 论坛 | 博客

OS

  • 博客访问: 2226314
  • 博文数量: 691
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 2660
  • 用 户 组: 普通用户
  • 注册时间: 2014-04-05 12:49
个人简介

不浮躁

文章分类

全部博文(691)

文章存档

2019年(1)

2017年(12)

2016年(99)

2015年(207)

2014年(372)

分类: 嵌入式

2015-03-28 20:05:12

Qt的事件模型一个强大的功能是一个QObject对象能够监视发送其他QObject对象的事件,在事件到达之前对其进行处理。

假设我们有一个CustomerInfoDialog控件,由一些QLineEdit控件组成。我们希望使用Space键得到下一个QLineEdit的输入焦点。一个最直接的方法是继承QLineEdit重写keyPressEvent()函数,当点击了Space键时,调用focusNextChild()

void MyLineEdit::keyPressEvent(QKeyEvent *event)

{

    if (event->key() == Qt::Key_Space) {

        focusNextChild();

    } else {

        QLineEdit::keyPressEvent(event);

    }

}

这个方法有一个最大的缺点:如果我们在窗体中使用了很多不同类型的控件(QComboBoxQSpinBox等等),我们也要继承这些控件,重写它们的keyPressEvent()。一个更好的解决方法是让CustomerInfoDialog监视其子控件的键盘事件,在监视代码处实现以上功能。这就是事件过滤的方法。实现一个事件过滤包括两个步骤:

1.      在目标对象上调用installEventFilter(),注册监视对象。

2.      在监视对象的eventFilter()函数中处理目标对象的事件。

注册监视对象的位置是在CustomerInfoDialog的构造函数中:

CustomerInfoDialog::CustomerInfoDialog(QWidget *parent)

    : QDialog(parent)

{

    ...

    firstNameEdit->installEventFilter(this);

    lastNameEdit->installEventFilter(this);

    cityEdit->installEventFilter(this);

    phoneNumberEdit->installEventFilter(this);

}

事件过滤器注册后,发送到firstNameEditlastNameEditcityEditphoneNumberEdit控件的事件首先到达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(event);

                 if (keyEvent->key() == Qt::Key_Space)
                 {

                    focusNextChild();

                   return true;

               }

          }

    }

    return QDialog::eventFilter(target, event);

}

//鼠标移到控件上和离开控件处理

bool CustomerInfoDialog::eventFilter(QObject *target, QEvent *event)

{

    if (target == firstNameEdit || target == lastNameEdit || target == cityEdit || target == phoneNumberEdit)
      
{

            if (event->type() == QEvent::Enter)//鼠标移动到控件上
            {

                       ..;

            }
          if(event->type() == QEvent::Leave)
          {
                  ....;
          }

          }

    }

    return QDialog::eventFilter(target, event);

}



阅读(4664) | 评论(0) | 转发(0) |
0

上一篇:shell 函数返回值的方法

下一篇:Qt中 Tab键

给主人留下些什么吧!~~