一、效果
1、点击“闪烁”按钮可以模拟消息闪动,点击后弹出消息详情对话框;
2、托盘右键菜单包括:“显示”和“关闭”。
3、双击托盘显示程序,关闭后隐藏到托盘。
二、源码
主要代码如下:
1 //初始化托盘 2 void Dialog::InitTray() 3 { 4 QMenu *contexMenu = new QMenu(this); //注意右键菜单的父对象,在窗口销毁后要把菜单也销毁掉 5 QAction *shutAction = new QAction("关闭",this); 6 shutAction->setIcon(QIcon(":/image/close.png")); 7 QAction *showAtion = new QAction("显示",this); 8 showAtion->setIcon(QIcon(":/image/show.png")); 9 10 contexMenu->addAction(shutAction); 11 contexMenu->addSeparator(); 12 contexMenu->addAction(showAtion); 13 14 connect(shutAction,SIGNAL(triggered()),this,SLOT(programExit())); //点击了这两个菜单 15 connect(showAtion,SIGNAL(triggered()),this,SLOT(ShowNormal())); 16 17 m_systemTray = new QSystemTrayIcon(this); 18 m_systemTray->setToolTip("Qt 托盘"); //放在图表上时候显示 19 m_systemTray->setContextMenu(contexMenu); 20 m_systemTray->setIcon(QIcon(":/image/qicon.png")); 21 m_systemTray->show(); 22 connect(m_systemTray,SIGNAL(activated(QSystemTrayIcon::ActivationReason)),this,SLOT(trayIconActived(QSystemTrayIcon::ActivationReason))); 23 //connect(m_systemTray, &QSystemTrayIcon::messageClicked, this, &Dialog::ShowMessageBox); 24 25 connect(timerT, &QTimer::timeout, this, &Dialog::sltTimerT); 26 connect(timerNoT, &QTimer::timeout, this, &Dialog::sltTimerNoT); 27 } 28 29 30 //托盘消息闪动 31 void Dialog::on_blingButton_clicked() 32 { 33 timerT->start(300); 34 m_bShowingMsg = true; 35 ui->blingButton->setEnabled(false); 36 ui->noblingButton->setEnabled(true); 37 } 38 39 void Dialog::on_noblingButton_clicked() 40 { 41 if (timerT->isActive()) 42 { 43 timerT->stop(); 44 } 45 46 if (timerNoT->isActive()) 47 { 48 timerNoT->stop(); 49 } 50 51 m_bShowingMsg = false; 52 ui->blingButton->setEnabled(true); 53 ui->noblingButton->setEnabled(false); 54 55 m_systemTray->setIcon(QIcon(":/image/qicon.png")); 56 m_systemTray->show(); 57 } 58 59 //刷新托盘图标 60 void Dialog::sltTimerT() 61 { 62 m_systemTray->setIcon(QIcon(":/image/qicon.png")); 63 timerNoT->start(300); 64 if(timerT->isActive()) 65 { 66 timerT->stop(); 67 } 68 } 69 70 void Dialog::sltTimerNoT() 71 { 72 m_systemTray->setIcon(QIcon(":/image/qicon_no.png")); 73 timerT->start(300); 74 if(timerNoT->isActive()) 75 { 76 timerNoT->stop(); 77 } 78 }
标签:systemTray,Qt,QSystemTrayIcon,托盘,timerT,Dialog,timerNoT,setIcon From: https://www.cnblogs.com/ybqjymy/p/16876249.html