I have an open Qt Mac app. I am clicking the app Icon
Is there a way to get a notification for this in the app?
The problem with QEvent::ApplicationActivate is that it will be emitted for every activation - eg., even if you switch to the app on Application Switcher. The native behavior is to show the app only on Dock icon click, not when you are switching by cmd+tab.
But, there is a hack that works at least for Qt 5.9.1. The Dock icon click produces 2 sequential QEvent::ApplicationStateChangeEvent events, meanwhile cmd+tab - only one. So, this code will emit Dock click signal quite accurately. App class is the application class inherited from QApplication and also an event filter for itself.
bool App::eventFilter(QObject* watched, QEvent* event)
{
#ifdef Q_OS_MACOS
if (watched == this && event->type() == QEvent::ApplicationStateChange) {
auto ev = static_cast(event);
if (_prevAppState == Qt::ApplicationActive
&& ev->applicationState() == Qt::ApplicationActive) {
emit clickedOnDock();
}
_prevAppState = ev->applicationState();
}
#endif // Q_OS_MACOS
return QApplication::eventFilter(watched, event);
}