[SOLVED] How to detect QStackedWidget focus?
I have a QStackedWidget and I need to know when it receives focus (in other words, when any of its child widgets receives focus). I've tried installing an event filter onto it:
@bool CMainWindow::eventFilter(QEvent * e, QObject* o)
if (e && e->type() == QEvent::FocusIn)
// FocusIn detected - do stuff
return QMainWindow::eventFilter(e, o);
Note that I don't even check the sender object, and I still never get the FocusIn event. How can I detect this event?
StackedWidget is not a user interactive control so it doesn't have a focus event. What you can do is to install the event filter on each child widget of it and filter for that, eg.
auto widgetIndex = ...
auto cldrn = stacWid->widget(widgetIndex)->findChildren<QWidget*>();
for(auto obj : cldrn)
EDIT: You can get a focus on the stacked widget by setting a focus policy of the relevant page frames to StrongFocus, but it will only gain focus via keybord, not mouse, and not when children gain focus, so my previous advice holds.
That is not a solution for me because I will dynamically add and remove widgets to and from StackedWidget. Installing event filter for each would require overriding the QStackedWidget and is pretty tedious, if at all possible. Is there no easier way?
Well focus events don't usually bubble up so there's no direct way to capture them in a parent (for the most part).
What you can do is, instead of filtering events, connect to the "QApplication::focusChanged":http://qt-project.org/doc/qt-5/qapplication.html#focusChanged signal and in the related slot check if the new widget with focus is a child of the relevant stacked widget page. You can do that by calling contains() on a findChildren() result (like in the example I gave earlier).
Thank you Chris, that's exactly what I was looking for!