When you click the "close button" of an application's window, on Mac OS X the window will be hidden but the application continue running. When you click on the Dock Icon, the application's window will be showed. This is the default behaviour for Mac Apps but Qt Apps doesn't the same. So, how we could implement this behaviour?
#ifndef _APPLICATION_H_
#define _APPLICATION_H_
// Qt4 Headers
include <QApplication>
include <QWidget>
// Carbon Headers
#ifdef Q_WS_MAC
#include <Carbon/Carbon.h>
#endif
class Application : public QApplication {
Q_OBJECT
public:
Application (int& argc, char **argv);
QWidget *mainWindow (void) const;
private:
QWidget *m_mainWindow;
#ifdef Q_WS_MAC
AEEventHandlerUPP m_appleEventProcessorUPP;
#endif
};
#endif // !_APPLICATION_H_
Here, we've implemented an Application class that Inherits from QApplication. This class contains a reference to the App's Main Window.
#ifdef Q_WS_MAC
static OSStatus appleEventProcessor(const AppleEvent *ae,
AppleEvent *event,
long handlerRefCon)
{
Application *app = (Application *) handlerRefCon;
OSType aeID = typeWildCard;
OSType aeClass = typeWildCard;
AEGetAttributePtr(ae, keyEventClassAttr, typeType, 0,
&aeClass, sizeof(aeClass), 0);
AEGetAttributePtr(ae, keyEventIDAttr, typeType, 0,
&aeID, sizeof(aeID), 0);
if (aeClass == kCoreEventClass) {
if (aeID == kAEReopenApplication) {
app->mainWindow()->show();
}
return noErr;
}
return eventNotHandledErr;
}
#endif
Application::Application (int& argc, char **argv)
: QApplication(argc, argv)
{
// Don't Quit the App on Window Close
setQuitOnLastWindowClosed(false);
// Initialize Main Window
m_mainWindow = new QLabel("Test Main Window");
#ifdef Q_WS_MAC
// Install Reopen Application Event (Dock Clicked)
m_appleEventProcessorUPP = AEEventHandlerUPP(appleEventProcessor);
AEInstallEventHandler(kCoreEventClass, kAEReopenApplication,
m_appleEventProcessorUPP, (long) this, true);
#endif
}
QWidget *Application::mainWindow (void) const {
return(m_mainWindow);
}
Thats all folks! Run the app, Click on close button and then click on the dock icon to see the result.