适用于 macOS 的 Qt 5.9.1 的系统托盘应用程序

System tray application with Qt 5.9.1 for macOS

本文关键字:系统 应用程序 macOS Qt 适用于      更新时间:2023-10-16

我想为macOS构建一个纯粹的基于系统托盘的应用程序,就像您从Dropbox或1Password mini中知道的那样。

目前,我已使用QGui应用程序C++代码,主要是隐藏停靠图标,并在单击系统托盘图标时提供比菜单更高级的视图。

这个问题已经在这里得到了回答,但我更喜欢使用 C++甚至QML的解决方案。
这在Qt中可能吗?我该怎么做?

在"更高级的视图"上,我无能为力,但是我最近实现了一个托盘图标应用程序。

void Launcher::InitializeTrayIcon() {
CreateTrayActions();
CreateTrayIcon();
}
void Launcher::CreateTrayActions() {
restoreAction = new QAction(tr("&Restore"), this);
connect(restoreAction, SIGNAL(triggered()), this, SLOT(showNormal()));
quitAction = new QAction(tr("&Quit"), this);
connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
openConfig = new QAction(tr("&Open Configuration"), this);
connect(openConfig, SIGNAL(triggered()), this, SLOT(openConfigFile()));
languageSelection = new QMenu(tr("Select Language"), this);
QIcon englishFlag(":/Resources/FlagEnglish.png");
activateEnglishLanguage = new QAction(englishFlag, tr("English"), this);
connect(activateEnglishLanguage, SIGNAL(triggered()), this,
SLOT(changeLanguageToEnglish()));
QIcon germanFlag(":/Resources/FlagGerman.png");
activateGermanLanguage = new QAction(germanFlag, tr("German"), this);
connect(activateGermanLanguage, SIGNAL(triggered()), this,
SLOT(changeLanguageToGerman()));
}
void Launcher::CreateTrayIcon() {
// Create Menu for Tray Icon
trayIconMenu = new QMenu(this);
languageSelection = trayIconMenu->addMenu(tr("Select Language"));
languageSelection->addAction(activateEnglishLanguage);
languageSelection->addAction(activateGermanLanguage);
trayIconMenu->addAction(restoreAction);
trayIconMenu->addAction(openConfig);
trayIconMenu->addSeparator();
trayIconMenu->addAction(quitAction);
// Create tray icon by passing its Menu
trayIcon = new QSystemTrayIcon(this);
trayIcon->setContextMenu(trayIconMenu);
// Add functionality on double click
connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this,
SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
SetTrayIconLogo();
trayIcon->show();
}
void Launcher::SetTrayIconLogo() {
QIcon icon(":/Resources/icon.ico");
trayIcon->setIcon(icon);
}

请注意,为了在单击窗口中的"关闭"图标时不关闭整个应用程序,您必须覆盖关闭事件:

void Launcher::closeEvent(QCloseEvent *event) {
hide();
event->ignore();
}

希望这有帮助。