Reputation: 1212
I'm making a simple game with Qt and I'd like to pause the game when the user switches to a different window (this could be by minimizing it or by accidentally clicking on a window beside it, etc). My game is wrapped in a QMainWindow, so I'd like to be able to detect when that loses focus.
I've tried a few different methods for this, but I haven't been successful. I first tried overloading QMainWindow's focusOutEvent, but this method was only called when I first gave the window focus with setFocus. I also tried to overload the window's event(QEvent *) method to check for QEvent::ApplicationActive and QEvent::ApplicationDeactivate.
I would post the code for my QMainWindow but there isn't much to show, I literally just tried to implement those two methods but neither were called. I did nothing else to set up those methods (maybe I'm missing a step?).
Does anyone know a good way to determine if your QMainWindow has "lost focus"?
Upvotes: 4
Views: 4222
Reputation: 2189
I had a similar need once, and resolved it by overloading 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) ;
}
Upvotes: 6
Reputation: 29166
From the documentation -
A widget normally must
setFocusPolicy()
to something other than Qt::NoFocus in order to receive focus events. (Note that the application programmer can callsetFocus()
on any widget, even those that do not normally accept focus.)
From this part of the documentation, about focusPolicy
-
This property holds the way the widget accepts keyboard focus.
The policy is
Qt::TabFocus
if the widget accepts keyboard focus by tabbing,Qt::ClickFocus
if the widget accepts focus by clicking,Qt::StrongFocus
if it accepts both, andQt::NoFocus
(the default) if it does not accept focus at all.You must enable keyboard focus for a widget if it processes keyboard events. This is normally done from the widget's constructor. For instance, the
QLineEdit
constructor callssetFocusPolicy
(Qt::StrongFocus
).
So set your focus policies accordingly, I guess then you will receive appropriate focus events.
Upvotes: 1