Qt 系统托盘

写了一个Qt 系统托盘类SystemTray:

Qt 系统托盘_第1张图片

用法:

systemTray = new SystemTray(this, ":trayicon/offline");

 

可重写createMenu定制复杂效果。   
运行即可得到一个简易系统托盘和简单响应,效果如下:

使用Linguist翻译成中文[Qt Linguist用法],效果如下:

使用qss 设置字体大小(微软雅黑12px) [Qt qss设置文件],效果如下:

 

SystemTray类:

.h

#ifndef SYSTEMTRAY_H
#define SYSTEMTRAY_H

#include <QAction>
#include <QMenu>
#include <QIcon>
#include <QWidget>
#include <QSystemTrayIcon>

class SystemTray : public QObject
{
    Q_OBJECT
public:
    explicit SystemTray(QWidget *w, const QString& iconFileName);
    
    void setTrayIcon(const QString &iconFileName);
    void setToolTip(const QString &tip);

    virtual void retranslate();
signals:

public slots:
    void iconActivated(QSystemTrayIcon::ActivationReason reason);
private:
    QWidget *widget;

    QIcon icon;
    QSystemTrayIcon *trayIcon;

    QAction *showAction;
    QAction *quitAction;

protected:
    QMenu *trayIconMenu;
    virtual void createMenu();
private:
    void createActions();
    void createTrayIcon();
};

#endif // SYSTEMTRAY_H


.cpp

#include "systemtray.h"
#include <QApplication>

#include <QCoreApplication>

SystemTray::SystemTray(QWidget *w, const QString &iconFileName) :
    QObject(), widget(w)
{
    icon = QIcon(iconFileName);
    createMenu();
    createTrayIcon();
    trayIcon->show();

    connect(trayIcon, &QSystemTrayIcon::activated, this, &SystemTray::iconActivated);

    retranslate();
}

void SystemTray::createMenu()
{
    showAction = new QAction(widget);
    connect(showAction, &QAction::triggered, widget, &QWidget::showNormal);

    quitAction = new QAction(widget);
    //connect(quitAction, &QAction::triggered, this, &SystemTray::quitTriggered);// 编译错误
    connect(quitAction, &QAction::triggered, &QApplication::quit);// 新的connect写法,允许省略接受者

    // 注意:trayIconMenu的父类为desktop,如果为this,则右键单击托盘不选中时,托盘菜单不消失。
    trayIconMenu = new QMenu((QWidget*)QApplication::desktop());

//    trayIconMenu->setStyleSheet("QMenu{font-size: 12px;}");

    trayIconMenu->addAction(showAction);
    trayIconMenu->addSeparator();
    trayIconMenu->addAction(quitAction);
}

void SystemTray::retranslate()
{
    showAction->setText(tr("show"));
    quitAction->setText(tr("quit"));
}

void SystemTray::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
    switch (reason) {
    case QSystemTrayIcon::Trigger: // 单击
    case QSystemTrayIcon::DoubleClick:// 双击
        widget->showNormal();
        break;
    case QSystemTrayIcon::MiddleClick:

        break;
    default:
        ;
    }
}

void SystemTray::createTrayIcon()
{
    trayIcon = new QSystemTrayIcon(this);
    trayIcon->setContextMenu(trayIconMenu);

    trayIcon->setIcon(icon);
    trayIcon->setToolTip("Tray tool tip");
}

void SystemTray::setTrayIcon(const QString &iconFileName)
{
    trayIcon->setIcon(QIcon(iconFileName));
}

void SystemTray::setToolTip(const QString &tip)
{
    trayIcon->setToolTip(tip);
}


 Tips: 注意,在注释的时候,请在// 空格再加注释,能避免解析错误。

 

 

 

 

你可能感兴趣的:(Qt 系统托盘)