QT, 系统托盘 及 菜单

通过 QSystemTrayIcon 和 QMenu 可以实现pc应用的系统托盘及菜单:

QSystemTrayIcon::setContextMenu(QMenu*);

关键代码(截取项目中的代码)如下:

cpp 复制代码
    //!系统托盘及菜单;
    m_sysTray = new QSystemTrayIcon(this);
    m_sysTray->setIcon(QIcon(GlobalSetting::Instance()->AppPath()+"/ico/DfaStudio/systemTrayIcon.png"));
    m_sysTray->setToolTip(Tr("MainWindow","Distributed Fiber Analyzer"));
    m_sysTray->show();

    QMenu* menu = new QMenu(this);
    QAction* showAction = new QAction(Tr("MainWindow","Show"),this);
    QAction* exitAction = new QAction(Tr("MainWindow","Exit"),this);
    menu->addAction(showAction);
    menu->addAction(exitAction);
    m_sysTray->setContextMenu(menu);
    //
    connect(showAction,&QAction::triggered,[this](){
        if(!this->isMaximized()){
            this->showMaximized();
        }
        else{
            this->showNormal();
        }
    });
    connect(exitAction,&QAction::triggered,[this](){
        if(this->dosomethingExiting()){
            qApp->quit();
        }
    });
    connect(m_sysTray,&QSystemTrayIcon::activated,[this](QSystemTrayIcon::ActivationReason reason){
        switch (reason) {
//        case QSystemTrayIcon::Trigger:
//        break;
        case QSystemTrayIcon::DoubleClick:
            if(!this->isMaximized()){
                this->showMaximized();
            }
            else{
                this->showNormal();
            }
            break;
        default:
            break;
        }
    });

这里添加了双击托盘图标放大/还原的功能,如上QSystemTrayIcon::activated() 信号;

如何要使托盘图标是动态的,可以加一个QTimer定时器,通过 m_sysTray->setIcon()不断更换图标,如QQ的来消息时的闪动,可以轮替两张大小相同的图片,一张透明,一张高亮。这样就有一闪一闪的效果。当然还可以设置其它动画,操作方法都一样,这里就不多讲述。

相关推荐
宏笋3 小时前
Qt开发了一款绘图和制作信笺的软件
qt
半杯咖啡半行码7 小时前
Qt 隐式共享(Implicit Sharing)深度解析:机制、陷阱与 Qt6迁移
开发语言·数据库·qt
慧都产品智能化1 天前
Qt 开发 CAD/CAM 工序表的隐性成本分析
c++·qt·qt5·qt6.3
ShineWinsu2 天前
对于Qt窗口:QMainWindow、QMenuBar、Qmenu、QAction的解析
c++·qt·菜单·qmainwindow·qaction·qmenu·qmenubar
ShineWinsu2 天前
对于Qt:QSpacerItem常见属性以及方法的解析
开发语言·c++·qt·面试·系统架构·客户端·qspaceritem
ShineWinsu2 天前
对于Qt:QGripLayout常见属性、方法以及QSizePolicy的解析
开发语言·c++·qt·面试·gui·客户端·网格
艾莉丝努力练剑2 天前
【QT】系统相关:TCP的API介绍
开发语言·前端·c++·人工智能·qt·学习·tcp/ip
ShineWinsu2 天前
对于Qt:QVBoxLayout常见属性以及方法的解析
开发语言·数据库·c++·qt·gui·客户端·布局管理器
ShineWinsu3 天前
对于Qt:QFormLayout常见属性以及方法的解析
开发语言·c++·qt·面试·客户端·表单·qformlayout
ShineWinsu4 天前
对于Qt:QHBoxLayout常见属性以及方法的解析
c++·qt·面试·gui·客户端·布局管理器·水平布局器