Vade
Vade

Reputation: 2029

adding eventfilter to QLineEdit changes its look

I have installed an EventFilter on my QLineEdit so that i might be able to process focus events to allow a QFileDialog to show when it gets focus.

i have added the following lines:

QLineEdit *projDir = new QLineEdit();

then further down i have:

projDir->installEventFilter(this)

and this is my function:

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

but for some reason when i have this filter the actual QLineEdit doesnt show as normal. you can tab to it and click on it but it doesn't look like normal. Screen shot: Screenshot of the QLineEdit which isnt displaying properly

thanks for any help

Upvotes: 2

Views: 6107

Answers (2)

Tim Meyer
Tim Meyer

Reputation: 12600

The return true/false statements from your answer are correct according to the Qt docs:

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.

However there are a couple of points to reconsider:

  • Your code contains code paths which do not contain a return statement: If the target is not projDirEdit, or the event is not FocusIn, what will be returned? True? False?
  • You shouldn't ignore() the event if you don't care about it, as that could mean other classes won't handle the event anymore.
  • Using a switch() for the event type allows easier extension if you want to filter out multiple events.

Personally, I would implement it like this:

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 );
}

Upvotes: 7

Vade
Vade

Reputation: 2029

Sorry but i worked out what i was doing wrong.

in the eventfilter i needed to add a return false and return true. i am not sure if that is correct but it fixed the problem for me:

    bool StartDialog::eventFilter(QObject *target, QEvent *event)
{
    if(target == projDirEdit )
    {
        if (event->type() == QEvent::FocusIn)
        {
            qDebug()<<"yep";
            return true;
        }
        else
        {
            event->ignore();
            return false;
        }
    }
}

Upvotes: 1

Related Questions