前言
有时候软件关闭,我们从系统栏也是能正常操作后台软件的,那么这个时候我们使用的其实托盘效果而已。
一、演示效果
二、关键程序
代码如下:
#include "QtWidgetsApplication1.h"
#include <QSystemTrayIcon>
#include <QMenu>
#include <QIcon>
QtWidgetsApplication1::QtWidgetsApplication1(QWidget *parent)
: QDialog(parent)
{
ui.setupUi(this);
QMenu *m = new QMenu(this);
QIcon icon(u8":/Resouce/托盘.png");
m_pSystemTray = new QSystemTrayIcon(this);
m_pSystemTray->setIcon(icon);
m_pSystemTray->setToolTip(u8"托盘测试");
m_pMinimumAct = new QAction(u8"最小化", this);
connect(m_pMinimumAct, SIGNAL(triggered()), this, SLOT(hide()));
m_pMaximumAct = new QAction(u8"最大化", this);
connect(m_pMaximumAct, SIGNAL(triggered()), this, SLOT(showMaximized()));
m_pRestoreAct = new QAction(u8"恢复窗口", this);
connect(m_pRestoreAct, SIGNAL(triggered()), this, SLOT(showNormal()));
m_pQuitAct = new QAction(u8"退出", this);
connect(m_pQuitAct, SIGNAL(triggered()), qApp, SLOT(quit()));
connect(m_pSystemTray, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(slotActivatedSysTrayIcon(QSystemTrayIcon::ActivationReason)));
QMenu *pContextMenu = new QMenu(this);
pContextMenu->addAction(m_pMinimumAct);
pContextMenu->addAction(m_pMaximumAct);
pContextMenu->addAction(m_pRestoreAct);
pContextMenu->addSeparator();
pContextMenu->addAction(m_pQuitAct);
m_pSystemTray->setContextMenu(pContextMenu);
m_pSystemTray->show();
close();
}
void QtWidgetsApplication1::closeEvent(QCloseEvent *event)
{
if (m_pSystemTray->isVisible())
{
hide();
m_pSystemTray->showMessage(u8"托盘", u8"该程序托盘正在运行!");
}
}
void QtWidgetsApplication1::slotActivatedSysTrayIcon(QSystemTrayIcon::ActivationReason reason)
{
switch (reason)
{
case QSystemTrayIcon::Trigger:
//单击托盘图标
break;
case QSystemTrayIcon::DoubleClick:
//双击托盘图标
//双击后显示主程序窗口
this->show();
break;
default:
break;
}
}