将eventfilter添加到QLineEdit会改变其外观

Vad*_*ade 2 qt

我已经安装了一个EventFilteron my,QLineEdit这样我就可以处理焦点事件,以便QFileDialog在获得焦点时显示.

我添加了以下几行:

QLineEdit *projDir = new QLineEdit();
Run Code Online (Sandbox Code Playgroud)

然后我进一步向下:

projDir->installEventFilter(this)
Run Code Online (Sandbox Code Playgroud)

这是我的功能:

bool StartDialog::eventFilter(QObject *target, QEvent *event)
{
    if(target == projDirEdit )
    {
        if (event->type() == QEvent::FocusIn)
        {
            qDebug()<<"yep";
        }
        else
            event->ignore();
    }
}
Run Code Online (Sandbox Code Playgroud)

但出于某种原因,当我有这个过滤器时,实际上QLineEdit并不显示正常.你可以选择它并单击它但它看起来不正常.截屏: 没有正确显示的QLineEdit的屏幕截图

谢谢你的帮助

Tim*_*yer 7

return true/false根据Qt文档,您的答案中的陈述是正确的:

在重新实现此函数时,如果要过滤掉事件,即停止进一步处理,则返回true; 否则返回false.

但是有几点需要重新考虑:

  • 您的代码包含不包含return语句的代码路径:如果目标不是projDirEdit,或者事件不是FocusIn,将返回什么?真正?假?
  • ignore()如果您不关心它,则不应该发生此事件,因为这可能意味着其他类将不再处理该事件.
  • 如果要过滤掉多个事件,则使用switch()作为事件类型可以更轻松地扩展.

就个人而言,我会像这样实现它:

bool StartDialog::eventFilter(QObject *target, QEvent *event)
{
    if( target == projDirEdit )
    {
        switch( event->type() )
        {
        case QEvent::FocusIn:
        case QEvent::FocusOut:  // I added this as an example why I use switch()
            event->ignore(); // not sure if this is necessary
            return true;
        default:
            break;
        };
    }

    // let the base class handle anything else
    // (assuming QFileDialog is the base class)
    return QFileDialog::eventFilter( target, event );
}
Run Code Online (Sandbox Code Playgroud)