通过 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的来消息时的闪动,可以轮替两张大小相同的图片,一张透明,一张高亮。这样就有一闪一闪的效果。当然还可以设置其它动画,操作方法都一样,这里就不多讲述。