开发者

Qt on Mac OS - Detecting a click on the dock menu

I am dropping the system tray icon for the Mac OS version of my applicatio开发者_Go百科n. 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(); 
    }


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜