| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- #include "ydtray.h"
- namespace ydTray {
- QSystemTrayIcon* g_trayIcon = nullptr;
- QMenu* g_trayMenu = nullptr;
- void installTray(QWidget* mainwindow) {
- if (!mainwindow)
- return;
- // if (!ydTray::isSubsys()) {
- // return;
- // }
- // 检查系统是否支持托盘
- if (!QSystemTrayIcon::isSystemTrayAvailable()) {
- //QMessageBox::critical(nullptr, "错误", "系统不支持托盘功能!");
- qDebug() << QString("错误, 系统不支持托盘功能!");
- }
- // 禁用程序退出时自动关闭托盘(默认关闭,需手动处理)
- QApplication::setQuitOnLastWindowClosed(false);
- // 1. 创建托盘图标
- g_trayIcon = new QSystemTrayIcon(mainwindow);
- // 设置托盘图标(可替换为自己的图标,支持 QIcon 格式)
- g_trayIcon->setIcon(QIcon(QPixmap(QStringLiteral(":/new/prefix1/ElcIcon.png")))/*mainwindow->windowIcon()*/); // 用主窗口图标
- g_trayIcon->setToolTip(QString("ElcServer")); // 鼠标悬停提示
- // 2. 创建托盘右键菜单
- g_trayMenu = new QMenu(mainwindow);
- // 菜单动作:显示主窗口
- QAction* showAction = new QAction(QString("显示窗口"), mainwindow);
- QObject::connect(showAction, &QAction::triggered, mainwindow, &QWidget::showNormal);
- // 菜单动作:隐藏主窗口
- QAction* hideAction = new QAction(QString("隐藏窗口"), mainwindow);
- QObject::connect(hideAction, &QAction::triggered, mainwindow, &QWidget::hide);
- // 菜单动作:退出程序
- QAction* quitAction = new QAction(QString("退出"), mainwindow);
- QObject::connect(quitAction, &QAction::triggered, mainwindow, &QWidget::close);
- // 添加动作到菜单
- g_trayMenu->addAction(showAction);
- g_trayMenu->addAction(hideAction);
- g_trayMenu->addSeparator(); // 分隔线
- g_trayMenu->addAction(quitAction);
- // 关联菜单到托盘图标
- g_trayIcon->setContextMenu(g_trayMenu);
- // 3. 托盘图标双击事件(如双击显示窗口)
- QObject::connect(g_trayIcon, &QSystemTrayIcon::activated,
- [=](QSystemTrayIcon::ActivationReason reason) {
- if (reason == QSystemTrayIcon::DoubleClick) {
- mainwindow->showNormal(); // 双击显示窗口
- }
- }
- );
- // 4. 显示托盘图标
- g_trayIcon->show();
- }
- void unstallTray() {
- if (!ydTray::isSubsys()) {
- return;
- }
- if (g_trayIcon) {
- g_trayIcon->hide();
- }
- if (g_trayMenu) {
- qDeleteAll(g_trayMenu->actions());
- g_trayMenu->deleteLater();
- }
- g_trayMenu = nullptr;
- if (g_trayIcon) {
- g_trayIcon->deleteLater();
- }
- g_trayIcon = nullptr;
- }
- bool isSubsys() {
- return QApplication::arguments().contains("-subsys");
- }
- void changeWindowStyle(QWidget* mainwindow /* = nullptr */) {
- if (!ydTray::isSubsys()) {
- return;
- }
- mainwindow->hide();
- mainwindow->setWindowFlags(mainwindow->windowFlags() | Qt::Tool);
- }
- }
|