说明
windows系统托盘增加图标和功能
C++ Qt
代码
#include <QApplication> #include <QSystemTrayIcon> #include <QMenu> #include <QMainWindow> int main(int argc, char *argv[]) { QApplication a(argc, argv); // 创建主窗口 QMainWindow mainWindow; mainWindow.setWindowTitle("My Application"); mainWindow.resize(640, 480); // 创建系统托盘图标 QSystemTrayIcon* trayIcon = new QSystemTrayIcon(); trayIcon->setIcon(QIcon(":/icon.png")); // 设置图标 trayIcon->setVisible(true); // 创建菜单 QMenu* menu = new QMenu(); QAction* showAction = new QAction("显示窗口", menu); QAction* hideAction = new QAction("隐藏窗口", menu); QAction* quitAction = new QAction("退出", menu); menu->addAction(showAction); menu->addAction(hideAction); menu->addSeparator(); menu->addAction(quitAction); // 将菜单添加到系统托盘图标中 trayIcon->setContextMenu(menu); // 监听系统托盘图标的activated信号 QObject::connect(trayIcon, &QSystemTrayIcon::activated, [&mainWindow](QSystemTrayIcon::ActivationReason reason){ if(reason == QSystemTrayIcon::Trigger){ // 判断是否是单击事件 if(mainWindow.isHidden()){ // 如果主窗口是隐藏的,则显示它 mainWindow.show(); }else{ // 如果主窗口是显示的,则隐藏它 mainWindow.hide(); } } }); // 监听菜单动作的triggered信号 QObject::connect(showAction, &QAction::triggered, &mainWindow, &QMainWindow::show); QObject::connect(hideAction, &QAction::triggered, &mainWindow, &QMainWindow::hide); QObject::connect(quitAction, &QAction::triggered, &a, &QApplication::quit); return a.exec(); }
运行效果
推荐一个零声学院项目课,个人觉得老师讲得不错,分享给大家: