QMainWindow window is no longer active

I am making a simple game with Qt, and I would like to pause the game when the user switches to another window (this could be minimizing or accidentally clicking on the window next to it, etc.). My game is wrapped in QMainWindow, so I would like to know when it will lose focus.

I tried several different methods for this, but I was not successful. I first tried to overload QMainWindow focusOutEvent, but this method was only called when I first gave window focus using setFocus. I also tried to overload the window event (QEvent *) method to check QEvent :: ApplicationActive and QEvent :: ApplicationDeactivate.

I would publish the code for my QMainWindow, but so far not much to show, I literally just tried to implement these two methods, but not one of them was called. I did nothing else to set up these methods (maybe I am missing a step?).

Does anyone know a good way to determine if your QMainWindow has β€œlost focus”?

+4
source share
3 answers

I had a similar need once and resolved it by overloading the event(QEvent*) method of my QMainWindow:

 bool MyMainWindow::event(QEvent * e) { switch(e->type()) { // ... case QEvent::WindowActivate : // gained focus break ; case QEvent::WindowDeactivate : // lost focus break ; // ... } ; return QMainWindow::event(e) ; } 
+6
source

From the documentation -

A widget usually needs setFocusPolicy() to something other than Qt :: NoFocus in order to receive focus events. (Note that an application programmer can call setFocus() on any widget, even those that usually do not accept focus.)

From this part of the documentation , about focusPolicy -

This property holds the way the widget accepts keyboard focus.

Qt::TabFocus if the widget accepts keyboard focus on tabbing, Qt::ClickFocus if the widget accepts focus by pressing, Qt::StrongFocus if it accepts both, and Qt::NoFocus (by default) if it does not accept focus.

You must enable the keyboard focus for the widget if it handles the Events keyboard. This is usually done from the widget constructor. For an instance, the QLineEdit constructor calls setFocusPolicy ( Qt::StrongFocus ).

So, set the appropriate focus policies, I assume that you get the corresponding focus events.

+1
source

Try QWidget::isActiveWindow() .

0
source

Source: https://habr.com/ru/post/1401733/


All Articles