QSystemTrayIcon类提供创建托盘和系统提示消息的功能。

QSystemTrayIcon类使用相对来说比较简单,网上例程很多,但是这里面也有坑:

  • 写托盘代码一定要加托盘图标进去,否则你不知道你的托盘是否正确显示了,(没显示或者显示了没看到)
  • 测试代码中可以将托盘图标的路径写为绝对路径,来验证代码是否正确
  • QSystemTrayIcon类的实例一定要是成员变量,不能是局部变量,否则不能正确显示

示例代码如下:mainwindown.c

#include "mainwindow.h"
#include <QMenu>
#include <QCloseEvent>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
        pSystemTray = new QSystemTrayIcon(this);

        m_pShowAction = new QAction(tr("显示"), this);

        trayIcon = new QMenu(this);
        trayIcon->addAction(m_pShowAction);

        // 设置系统托盘的上下文菜单
        pSystemTray->setContextMenu(trayIcon);

        // 设置系统托盘提示信息、托盘图标
        pSystemTray->setToolTip(tr("我就是托盘"));
        pSystemTray->setIcon(QIcon("C:\\Users\\cjw\\Desktop\\tuopan\\tuopan\\debug\\ICO.png"));

        // 连接信号槽
        connect(m_pShowAction, &QAction::triggered, this, &QWidget::showNormal);
        connect(pSystemTray , SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(onActivated(QSystemTrayIcon::ActivationReason)));

        // 显示系统托盘

        pSystemTray->show();

        // 显示系统托盘提示信息
        pSystemTray->showMessage(tr("托盘标题"), tr("托盘显示内容"));

}

MainWindow::~MainWindow()
{

}


// 显示窗体
void MainWindow::showWindow()
{
    showNormal();
    raise();
    activateWindow();
}

// 激活系统托盘
void MainWindow::onActivated(QSystemTrayIcon::ActivationReason reason)
{
    switch(reason)
    {
    // 单击托盘显示窗口
    case QSystemTrayIcon::Trigger:
    {
        showNormal();
        raise();
        activateWindow();
        break;
    }
    // 双击
    case QSystemTrayIcon::DoubleClick:
    {
        // ...
        break;
    }
    default:
        break;
    }
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    if (pSystemTray->isVisible()) {
            //不退出App
            hide();
            event->ignore();
        }

}

mainwindown.c

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QSystemTrayIcon>
#include <QAction>

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = 0);
    ~MainWindow();

protected slots:
    void showWindow();
    void onActivated(QSystemTrayIcon::ActivationReason reason);
    void closeEvent(QCloseEvent *event);

private:
    QAction *m_pShowAction;
    QMenu *trayIcon;
    QSystemTrayIcon *pSystemTray;

};

#endif // MAINWINDOW_H

main.c

#include "mainwindow.h"
#include <QApplication>
#include <QMessageBox>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    if (!QSystemTrayIcon::isSystemTrayAvailable()) {
            QMessageBox::critical(0, QObject::tr("系统托盘"),
                                  QObject::tr("本机系统上检测不到任何系统托盘"));
            return 1;
        }




    QApplication::setQuitOnLastWindowClosed(false);  //关闭最后一个窗口不退出程序

    MainWindow w;
    w.show();

    return a.exec();
}

经过测试,该类在windowns和macOS平台上均适用,测试QT版本5.12和5.9.9。