【QT常用技术讲解】QSystemTrayIcon系统托盘
前言
项目中需要提供窗口的服务时,就会用到系统托盘。系统托盘支持右键菜单,也支持(左下角)系统消息提醒等实用的功能。
效果图
如上,本文的讲解包括3个功能:
- 显示消息:显示右下角的系统提醒消息;
- 关于:弹出一个对话框,代表打开第三方应用窗口;
- 退出:关闭系统托盘。
功能讲解
第一步,必须设置图标,不然系统图标出不来
//先创建qrc资源文件,新增图片到/目录下 //设置图标setIcon(QIcon(":/default.png"));
创建右键菜单,与MainWindow中应用窗口中的右键菜单是一样的QMenu+QAction
//第一步:QMenu + QAction 设置菜单及功能QMenu *menu = new QMenu();QAction *showMsgAction = new QAction("显示系统提醒消息", this);QAction *aboutAction = new QAction("弹出对话框", this);QAction *quitAction = new QAction("退出", this);menu->addAction(showMsgAction);menu->addSeparator();menu->addAction(aboutAction);menu->addAction(quitAction);//第二步:把以上菜单设置为右键菜单setContextMenu(menu);//设置右键菜单//第三步:设置菜单响应的槽(函数)connectQObject::connect(showMsgAction, &QAction::triggered, [&](){showMessage("提示", "这是系统托盘消息",QSystemTrayIcon::Information, 3000);});QApplication::setQuitOnLastWindowClosed(false);//显式禁用自动退出connect(aboutAction, &QAction::triggered, this, &TrayIcon::showAbout);connect(quitAction, &QAction::triggered, qApp, &QApplication::quit);
需要特别注意的是,使用自带的函数showMessage,可以直接在右下角弹出系统消息框,而使用QMessageBox弹出对话框框之前,必须如下声明,不然,当关闭QMessageBox对话框之后,就默认关闭系统托盘了。
QApplication::setQuitOnLastWindowClosed(false);//显式禁用自动退出
源码
//trayicon.h
#ifndef TRAYICON_H
#define TRAYICON_H#include <QObject>
#include <QSystemTrayIcon>class TrayIcon : public QSystemTrayIcon
{Q_OBJECT
public:explicit TrayIcon(QObject *parent = nullptr);void createTrayMenu();private slots:void showAbout();
private:void setpng(const QString& Path);
};#endif // TRAYICON_H
//trayicon.cpp
#include "trayicon.h"
#include <QMenu>
#include <QAction>
#include <QApplication>
#include <QMessageBox>
#include <QFile>
#include <QDir>TrayIcon::TrayIcon(QObject *parent): QSystemTrayIcon(parent)
{//设置图标setIcon(QIcon(":/default.png"));//创建右键菜单createTrayMenu();}void TrayIcon::createTrayMenu()
{QMenu *menu = new QMenu();QAction *showMsgAction = new QAction("显示系统提醒消息", this);QAction *aboutAction = new QAction("弹出对话框", this);QAction *quitAction = new QAction("退出", this);menu->addAction(showMsgAction);menu->addSeparator();menu->addAction(aboutAction);menu->addAction(quitAction);setContextMenu(menu);//设置右键菜单QObject::connect(showMsgAction, &QAction::triggered, [&](){showMessage("提示", "这是系统托盘消息",QSystemTrayIcon::Information, 3000);});QApplication::setQuitOnLastWindowClosed(false);//显式禁用自动退出connect(aboutAction, &QAction::triggered, this, &TrayIcon::showAbout);connect(quitAction, &QAction::triggered, qApp, &QApplication::quit);
}void TrayIcon::showAbout()
{QMessageBox::about(nullptr, "关于", "这是对话框");
}void TrayIcon::setpng(const QString& Path){QString absPath = QDir::toNativeSeparators(Path);if(QFile::exists(absPath)) {setIcon(QIcon(absPath));setToolTip("Application Tray");} else {//qWarning() << "Icon not found:" << absPath;}
}
//main.cpp
#include <QApplication>
#include "trayicon.h"int main(int argc, char *argv[])
{QApplication app(argc, argv);TrayIcon tray;tray.show();return app.exec();
}