诡异的Qt eventFilter

Qt Creator开发环境中,由于事件过滤不当,导致界面组件无法正常显示(QLineEdit不显示)

先看代码:

(1)安装事件过滤器

LocationDialog::LocationDialog(FooApplication * app, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::LocationDialog),
    m_app(app)
{
    ui->setupUi(this);

    ……

    //触发键盘
    ui->txt_query->installEventFilter(this);
    ui->txt_place2->installEventFilter(this);
    ui->txt_contactPerson->installEventFilter(this);
    ui->txt_contactNumber->installEventFilter(this);

    ……
}
(2)重载事件过滤

bool LocationDialog::eventFilter(QObject *obj, QEvent *event) {

    if(event->type() == QEvent::FocusIn) {

        if(obj->objectName().compare("txt_query")==0) {
            isActivited = true;
        }

        if(isActivited) {
            startProcess("FreeVK");
        }
    } else {
        QObject::eventFilter(obj, event);
    }
    return (true);
}

界面效果是这样的:QLineEdit显示不出来了!!!

起初还以为是组件的Z-ORDER问题,后来又以为是透明色的问题,结果怎么修改styleSheet都没用。

最后还是通过Qt助手,查看相关的帮助文档:

bool QObject::eventFilter ( QObject * watched, QEvent * event ) [virtual]
Filters events if this object has been installed as an event filter for the watched object.

In your reimplementation of this function, if you want to filter the event out, i.e. stop it being handled further, return true; otherwise return false.
意思就是说,如果你想将目标事件过滤出来,阻止进行后一步动作,就返回true;否则(进行后一步动作)就返回false。


代码中返回了true,导致Qt框架不再对应用程序的其他事件进行处理,除了FoucsIn,从而导致QLineEdit可能没被重绘。


(3)修改后的代码:

bool LocationDialog::eventFilter(QObject *obj, QEvent *event) {

    if(event->type() == QEvent::FocusIn) {

        if(obj->objectName().compare("txt_query")==0) {
            isActivited = true;
        }

        if(isActivited) {
            startProcess("FreeVK");
        }
    }

    //@2015-09-29 不能简单return(true)
    //返回true是阻止进一步处理,false是进行进一步处理
    return QObject::eventFilter(obj, event);
}

(4)界面效果

这下QLineEdit显示正常了!!


后记:对于该问题花费了近半个小时的时间纠结,体会就是,对于这些知其然而不知其所以然的问题,

还是要使用严谨的态度去分析,而且要分析透彻。当时点一下水,可能没遇上问题就PASS了,但总会有一天会遇到麻烦,而且习惯成自然,让你压根都不觉得这个问题是错误的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值