4

I am dropping the system tray icon for the Mac OS version of my application. However there's one small problem: when the user closes the main window the application is supposed to continue to run on the background and the main window should become visible again if the user clicks the dock icon. So far I have found no way of intercepting this click on the icon.

Is there any way to accomplish this with Qt? If not, how should I proceed with the native API to implement this behavior?

I have tried to create a custom application class that implement QApplication so that I can re-implement the macEventFilter but the documentation on this function is scarce.

application.h:

#ifndef APPLICATION_H
#define APPLICATION_H

#include <QApplication>

class QWidget;

class Application : public QApplication
{
    Q_OBJECT

public:

    Application(int, char*[]);
    void setMainWidget(QWidget*);
    bool macEventFilter(EventHandlerCallRef, EventRef);

private:
    QWidget *mainWidget;
};

#endif // APPLICATION_H

application.cpp:

#include <Application.h>
#include <QWidget>

Application::Application(int argc, char *argv[])
    : QApplication(argc, argv)
{
}

void Application::setMainWidget(QWidget *mainWidget)
{
    this->mainWidget = mainWidget;
}

bool Application::macEventFilter(EventHandlerCallRef, EventRef)
{
    mainWidget->show();
    return false;
}

main.cpp:

    #include <QtCore>
    #include <Application.h>
    #include "mainwidget.h"

    int main(int argc, char *argv[]) {
        Application a(argc, argv);

        MainWidget mainWidget;

    #ifdef Q_WS_MAC

        a.setWindowIcon(QIcon(":/resource/army-officer-icon.png"));

    #endif

        a.setMainWidget((QWidget*)&mainWidget);

        mainWidget.show();

        return a.exec(); 
    }
Raphael
  • 7,972
  • 14
  • 62
  • 83
  • Hi Raphael, probably too late but I think what's youre looking for was giver there : https://stackoverflow.com/a/15363738/7252834 Best regards – Romain Cendre Apr 01 '21 at 08:19
  • 1
    @RomainCendre thanks for reminding me that I used to do QT development over one decade ago. This definitely felt like a blast from the past and brought back some memories! – Raphael Apr 01 '21 at 16:37

1 Answers1

0

You need to reimplement the closeEvent() for your window, then check to see if the event came from the X button or somewhere else.

Christophe Weis
  • 2,518
  • 4
  • 28
  • 32
Thomas Havlik
  • 1,378
  • 4
  • 12
  • 20
  • What I'm trying to do is the contrary. I have already reimplemented the closeEvent() to hide my window but when I click the dock icon the window does not return to it's visible state. Merry christmas for you too – Raphael Dec 25 '10 at 05:43
  • 1
    Is it launching a new program instead? – Thomas Havlik Dec 25 '10 at 05:57
  • No, my program continues to run with it's main window hidden. Clicking the dock icon does absolutely nothing. – Raphael Dec 26 '10 at 13:39