You can check the focus on widgets using the hasFocus() function. focus property whether the widget has keyboard focus or not. You can also get the current application widget with focus using QApplication::focusWidget() . You can get a pointer to a focused widget, for example:
QWidget * fw = qApp->focusWidget();
When changing the focused widget, the signal QApplication::focusChanged(QWidget *old, QWidget *now) is issued. You can connect it to the slot in which you do what you like, depending on the change in focus.
source share