1.头文件
#pragma once
#include <QtWidgets/QMainWindow>
#include "ui_QtGuiApplication1.h"
#include <QSystemTrayIcon>
class QtGuiApplication1 : public QMainWindow
{
Q_OBJECT
public:
QtGuiApplication1(QWidget *parent = Q_NULLPTR);
private:
Ui::QtGuiApplication1Class ui;
public:
QSystemTrayIcon* m_sysTrayIcon;
QMenu* m_menu;
QAction* m_showWindow;
QAction* m_exit;
public:
void createActions(); //创建菜单按钮
void createMenu(); //创建菜单
private slots:
void activatedSysTrayIcon(QSystemTrayIcon::ActivationReason reason);
void showWindow(); //显示窗口
void exitApplication(); //退出程序
};
2.源文件
#include "QtGuiApplication1.h"
#include <QIcon>
QtGuiApplication1::QtGuiApplication1(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
m_sysTrayIcon = new QSystemTrayIcon(this);
QIcon icon = QIcon(":/Resources/5.jpg"); //新建托盘要显示的icon(没有图片不会在任务栏显示)
m_sysTrayIcon->setIcon(icon); //设置图标
m_sysTrayIcon->setToolTip(QStringLiteral("测试系统托盘图标")); //当鼠标移动到托盘上的图标时,会显示此处设置的内容
//给QSystemTrayIcon添加槽函数
connect(m_sysTrayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(on_activatedSysTrayIcon(QSystemTrayIcon::ActivationReason)));
createActions();
createMenu();
m_sysTrayIcon->show(); //在系统托盘显示此对象
}
void QtGuiApplication1::activatedSysTrayIcon(QSystemTrayIcon::ActivationReason reason)
{
switch (reason) {
case QSystemTrayIcon::Trigger:
m_sysTrayIcon->showMessage(QStringLiteral("测试"),QStringLiteral("欢迎使用此程序"),
QSystemTrayIcon::Information,1000);
break;
case QSystemTrayIcon::DoubleClick:
this->show();
break;
default:
break;
}
}
void QtGuiApplication1::createActions()
{
m_showWindow = new QAction(QStringLiteral("显示主界面"), this);
connect(m_showWindow, SIGNAL(triggered()), this, SLOT(showWindow()));
m_exit = new QAction(QStringLiteral("退出"), this);
connect(m_exit, SIGNAL(triggered()), this, SLOT(exitApplication()));
}
void QtGuiApplication1::createMenu()
{
m_menu = new QMenu(this);
m_menu->addAction(m_showWindow);
m_menu->addSeparator();
m_menu->addAction(m_exit);
m_sysTrayIcon->setContextMenu(m_menu);
}
void QtGuiApplication1::showWindow()
{
this->show();
}
void QtGuiApplication1::exitApplication()
{
exit(0);
}
3.测试结果
image.png