加入 setWindowFlags(Qt::Tool); 这条代码可以解决这两个问题,
1、窗口下方任务栏中无程序图标显示
2、当只有一个窗口的时候且创建了托盘图标的时候,使用hide()隐藏窗口不会让程序直接退出。
托盘详细操作请进入这篇文章:https://blog.csdn.net/qq_41768362/article/details/110901154
效果图:
Widget示例代码
#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
#include <QPushButton>
#include <QSystemTrayIcon>
#include <QMenu>
#include <QAction>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
QPushButton* hideBtn = new QPushButton(QStringLiteral("隐藏窗口"),this);
connect(hideBtn, &QPushButton::clicked, [&]()
{
this->hide();
});
setWindowFlags(Qt::Tool);
CreateSystemTrayIcon(); //创建托盘
}
Widget::~Widget()
{
delete ui;
}
void Widget::CreateSystemTrayIcon()
{
//初始化两个项目
QAction* showAction = new QAction(QStringLiteral("显示"));//项1
QAction* exitAction = new QAction(QStringLiteral("退出"));//项2
//项1的点击槽函数
connect(showAction, &QAction::triggered, this, [=]()
{
this->show();
});
//项2的点击槽函数
connect(exitAction , &QAction::triggered, this, [=]()
{
qDebug()<<"exit";
QApplication::exit(0);
});
//初始化菜单并添加项
QMenu* trayMenu = new QMenu(this);//菜单
trayMenu->addAction(showAction);
trayMenu->addAction(exitAction );
//创建一个系统托盘
QSystemTrayIcon* trayIcon = new QSystemTrayIcon(this);
trayIcon->setIcon(QIcon("C:\\Users\\admin\\Downloads\\server.ico")); //设置托盘图标
trayIcon->setContextMenu(trayMenu); //设置菜单
trayIcon->show();
}