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

时间:2017-07-31 06:41:24

标签: c++ qt qml

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

目前我的C ++代码带有QGuiApplication,主要的是隐藏停靠栏图标,并提供比单击系统托盘图标时菜单更高级的视图。

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

1 个答案:

答案 0 :(得分:0)

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

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();
}

希望这有帮助。