一.前言
工作中,有些用户喜欢点击最小化的时候,软件图标显示到右下角(系统托盘),并想增加一些菜单,双击又还原窗口,故此把系统托盘功能单独拿出来,以此做个记录
二.实现过程
1.核心是利用Qt提供的QSystemTrayIcon
2.核心代码,附带注释
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_pushButton_clicked()
{
systemIcon = new QSystemTrayIcon();
// 设置提示语
systemIcon->setToolTip("这是系统系统图标");
// 设置图标
systemIcon->setIcon(QIcon("://Icon.png"));
// 增加托盘菜单
QMenu *menu = new QMenu();
QAction *a1 = new QAction("菜单1");
QAction *a2 = new QAction("菜单2");
menu->addAction(a1);
menu->addAction(a2);
systemIcon->setContextMenu(menu);
connect(a1,SIGNAL(triggered(bool)),this,SLOT(onA1(bool)));
connect(a2,SIGNAL(triggered(bool)),this,SLOT(onA2(bool)));
// 关联拖盘事件
connect(systemIcon,SIGNAL(activated(QSystemTrayIcon::ActivationReason)),this,SLOT(onActivated(QSystemTrayIcon::ActivationReason)));
//
systemIcon->show();
// 要在show之后调用
systemIcon->showMessage("showMessage","系统托盘提示",QSystemTrayIcon::MessageIcon::Information,500);
}
void Widget::onActivated(QSystemTrayIcon::ActivationReason action)
{
qDebug()<<action;
if(action==QSystemTrayIcon::ActivationReason::Unknown){
qDebug()<<"未知点击";
}
else if(action==QSystemTrayIcon::ActivationReason::Context || action==QSystemTrayIcon::ActivationReason::Trigger){
qDebug()<<"鼠标单击";
}
else if(action==QSystemTrayIcon::ActivationReason::DoubleClick){
qDebug()<<"鼠标双击";
}
else if(action==QSystemTrayIcon::ActivationReason::MiddleClick){
qDebug()<<"鼠标中间单击";
}else{
return;
}
}
void Widget::onA1(bool b)
{
qDebug()<<"这是菜单1";
}
void Widget::onA2(bool b)
{
qDebug()<<"这是菜单2";
}
3.效果
三.源码下载链接