1. 在.cpp中引入头
#include <QSystemTrayIcon>
#ifdef Q_OS_MAC
#include <objc/objc.h>
#include <objc/message.h>
void setupDockClickEvent();
bool applicationShouldHandleReopen(id self,SEL _cmd,...);
#endif
2. Swizzling在mac端替换系统方法,监控mac端dock按钮点击
#ifdef Q_OS_MAC
bool applicationShouldHandleReopen(id self,SEL _cmd, ...)
{
action_showMain();
return false;
}
#endif
#ifdef Q_OS_MAC
void setupDockClickEvent()
{
Class cls = objc_getClass("NSApplication");
id appInstance = objc_msgSend(cls, sel_registerName("sharedApplication"));
if(appInstance != nullptr)
{
id appDelegate = objc_msgSend(appInstance, sel_registerName("delegate"));
Class delClass = objc_msgSend(appDelegate, sel_registerName("class"));
SEL shouldHandle = sel_registerName("applicationShouldHandleReopen:hasVisibleWindows:");
if (class_getInstanceMethod(delClass, shouldHandle))
{
if (class_replaceMethod(delClass, shouldHandle, reinterpret_cast<IMP>(applicationShouldHandleReopen), "B@:"))
qDebug() << "方法替换成功";
else
qDebug() << "方法替换失败";
}
else
{
if (class_addMethod(delClass, shouldHandle, reinterpret_cast<IMP>(applicationShouldHandleReopen),"B@:"))
qDebug() << "添加dock点击方法成功";
else
qDebug() << "添加dock点击方法成功失败";
}
}
}
#endif
3. 添加QSystemTrayIcon
trayicon = new QSystemTrayIcon(this);
trayicon->setToolTip("垣连");
#if defined(Q_OS_WIN)
trayicon->setIcon(QIcon(":/icon/images/icon.png"));
trayMenu = new TrayIconMenu();
QAction *main_action = new QAction(tr("打开主屏幕"),this);
QAction *exit_action = new QAction(tr("退出"),this);
QObject::connect(main_action,SIGNAL(triggered()),this,SLOT(action_showMain()));
QObject::connect(exit_action,SIGNAL(triggered()),this,SLOT(action_exit()));
trayMenu->addAction(exit_action);
trayMenu->addAction(main_action);
trayicon->setContextMenu(trayMenu);
#elif defined(Q_OS_MACOS)
setupDockClickEvent();
trayicon->setIcon(QIcon(":/icon/images/icon_mac.png"));
#endif
QObject::connect(trayicon,SIGNAL(activated(QSystemTrayIcon::ActivationReason)),this,SLOT(iconActived(QSystemTrayIcon::ActivationReason)));
trayicon->show();
4. 点击dock按钮和头部icon将页面展示在最前边
void action_showMain()
{
if (this->isMinimized()) this->showNormal();
if (this->isHidden()) this->show();
this->setWindowState(Qt::WindowActive);
this->raise();
this->activateWindow();
}
void action_exit()
{
qApp->quit();
}