其他分享
首页 > 其他分享> > QT 最小化到托盘

QT 最小化到托盘

作者:互联网

1.添加头文件和成员变量

mainWindow.h

#include <QSystemTrayIcon>  //t托盘类
#include <QDesktopServices> //桌面事件类
#include <QAction>
#include <QMenu>

private:
    QMenu *trayMenu;//托盘菜单
    QSystemTrayIcon *tray;//托盘图标添加成员
    QAction *restoreAction;//托盘图标右键点击时弹出选项
    QAction *quitAction;//托盘图标右键点击时弹出选项

2.初始化成员变量

mainWindow.cpp

    //***托盘***
    tray= new QSystemTrayIcon(this);//初始化托盘对象tray
    tray->setIcon(QIcon(QPixmap(":/icon/appIcon.png")));//设定托盘图标,引号内是自定义的png图片路径
    tray->setToolTip("进程计时器"); //提示文字
    QString title="APP Message";
    QString text="进程计时器";
    tray->show();//让托盘图标显示在系统托盘上
    tray->showMessage(title,text,QSystemTrayIcon::Information,3000); //最后一个参数为提示时长,默认10000,即10s

    restoreAction = new QAction("打开", this);
    connect(restoreAction, SIGNAL(triggered()), this, SLOT(show()));
    quitAction = new QAction("退出", this);
    connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));

    trayMenu = new QMenu(this);
    trayMenu->addAction(restoreAction);
    trayMenu->addSeparator();
    trayMenu->addAction(quitAction);
    tray->setContextMenu(trayMenu);

托盘图标右键点击菜单对应的槽函数可以根据自己的需求去写。

3.添加双击托盘图标打开窗口功能

3.1 添加槽函数

void Widget::showWidget(QSystemTrayIcon::ActivationReason reason)
{
    switch(reason)
    {
    case QSystemTrayIcon::Trigger://单击托盘图标
        break;
    case QSystemTrayIcon::DoubleClick://双击托盘图标
        this->showNormal();
        break;
    default:
        break;
    }
}

3.2 连接信号和槽

connect(tray,SIGNAL(activated(QSystemTrayIcon::ActivationReason)),this,SLOT(showWidget(QSystemTrayIcon::ActivationReason reason)));

之后就可以双击托盘图标打开隐藏的窗口了。

标签:QT,trayMenu,QSystemTrayIcon,托盘,最小化,include,tray,图标
来源: https://www.cnblogs.com/leocc325/p/13507349.html