QT笔记- QSystemTrayIcon系统托盘功能完整示例

时间:2024-12-19 07:12:15

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()); // 在鼠标当前位置弹出菜单
    }
}