1. 创建托盘对象
// 创建托盘图标QSystemTrayIcon * trayIcon = new QSystemTrayIcon(this);QIcon icon("://icon/test.png");trayIcon->setIcon(icon);trayIcon->show();trayIcon->connect(trayIcon, &QSystemTrayIcon::activated,this, &MainWindow::_activated);setWindowFlags(this->windowFlags() | Qt::Tool); // 设置窗口为Qt::Tool类型
2. _activated()槽函数
void MainWindow::_activated(QSystemTrayIcon::ActivationReason reason)
{if(reason == QSystemTrayIcon::DoubleClick){if(isVisible()){activateWindow();} else {show();}} else if(reason == QSystemTrayIcon::Context){QMenu menu;QAction * closeAction = new QAction("Close", this);// 连接关闭程序的信号槽,当点击该动作时,关闭整个应用程序QObject::connect(closeAction, &QAction::triggered, qApp, &QApplication::quit);menu.addAction(closeAction);menu.exec(QCursor::pos()); // 在鼠标当前位置弹出菜单}
}