QT: 最小化窗口到托盘图标

加入 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();
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值