要写一个可以隐藏到托盘的Qt 界面程序可以分三步:
-
在mainwindow.cpp 中添加头文件: #include <QSystemTrayIcon>
-
挑选一个顺眼的icon ,添加到qrc 中,比如笔者选择了:/icon/办公软件.png ; -
把以下代码粘贴到mainwindow.cpp 的构造函数中,把icon 换成自己的,大功告成~
QApplication::setQuitOnLastWindowClosed(false);
QSystemTrayIcon *icon = new QSystemTrayIcon(this);
icon->setIcon(QIcon(":/icon/办公软件.png"));
QMenu *menu = new QMenu;
QAction *normal, *min, *max, *quit;
normal = new QAction("显示主界面");
connect(normal, &QAction::triggered, [&](){
showNormal();
});
min = new QAction("最小化");
connect(min, &QAction::triggered, [&](){
showMinimized();
});
max = new QAction("最大化");
connect(max, &QAction::triggered, [&](){
showMaximized();
});
quit = new QAction("退出");
connect(quit, &QAction::triggered, [&](){
QCoreApplication::quit();
});
menu->addAction(normal);
menu->addAction(min);
menu->addAction(max);
menu->addSeparator();
menu->addAction(quit);
icon->setContextMenu(menu);
connect(icon, &QSystemTrayIcon::activated, [=](QSystemTrayIcon::ActivationReason r){
if(r == QSystemTrayIcon::ActivationReason::Trigger) emit normal->triggered();
});
icon->show();
|