-->

in Qt, what QEvent means loses window focus, regai

2020-07-14 10:26发布

问题:

I need to set transparency when my application loses focus. I also need to reset the transparency when it regains focus (from a mouse click or alt-tab or whatever)

I know how to set the transparency, so that is not the issue: setWindowOpacity(0.75);

The issue is WHEN?

回答1:

I agree with Kévin Renella that there are sometimes issues with QWidget::focusInEvent and QWidget::focusOutEvent. Instead, a better approach would be to implement QWidget::changeEvent():

void MyQWidget::changeEvent(QEvent *event)
{   
    QWidget::changeEvent(event);
    if (event->type() == QEvent::ActivationChange)
    {
        if(this->isActiveWindow())
        {
            // widget is now active
        }
        else
        {
            // widget is now inactive
        }
    }
}

You can also achieve the same thing by installing an event-filter. See The Event System on Qt Documentation for more information.



回答2:

When a QFocusEvent event occurs. Just re-implement

void QWidget::focusInEvent ( QFocusEvent * event );
void QWidget::focusOutEvent ( QFocusEvent * event );

from QWidget. Make sure to always call the super-class method before or after doing your work. i.e., (before case)

void Mywidget::focusInEvent (QFocusEvent * event ){
   QWidget::focusInEvent(event);
   // your code
}

But, there are sometimes issues with QWidget::focusInEvent and QWidget::focusOutEvent. See this answer for a more reliable approach.



回答3:

There are sometimes issues with QWidget::focusInEvent and QWidget::focusOutEvent events of QWidget

There is an alternative using QWidget::windowActivationChange(bool state). True, your widget is active, false otherwise.



标签: qt