Subscribing to Apple events in Qt
-
22-02-2021 - |
Question
Following the the code linked from here: Trap click event on dock icon using Qt on Mac, I tried to call the following method directly in my QApplication's constructor to receive notification of dock icon click events:
[[NSAppleEventManager sharedAppleEventManager]
setEventHandler: m_dockIconClickEventHandler
andSelector: @selector(handleDockClickEvent:withReplyEvent:)
forEventClass: kCoreEventClass
andEventID: kAEReopenApplication];
If I call it directly, I do not receive notifications of this event. However, if I call it using QTimer::singleShot
with a delay of, say, 5000 ms, I receive the notifications just fine.
Also, according to the Qt documentation, "A QTimer with a timeout interval of 0 will time out as soon as all the events in the window system's event queue have been processed." So I tried 0 ms, but that didn't work. 1 or above seems to.
Why do I need to wait and what is a better way to handle this situation than delaying for n ms?
Solution
When your application exec() is called, Qt sets its own event handlers, so your handler is overriden. You may use in your constructor
connect(this, SIGNAL(setupDockEventMonitor()), SLOT(onSetupDockEventMonitor()), Qt::QueuedConnection);
emit setupDockEventMonitor();
And in onSetupDockEventMonitor() do install this event handler.