Qt實現windows系統托盤例子

轉載自:http://www.qtcn.org/bbs/read-htm-tid-85563.html,感謝原作者分享

#ifndef WIDGET_H
#define WIDGET_H

#include <QtWidgets>

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT
public:
    explicit Widget(QWidget *parent = nullptr);
    ~Widget();

private:
    Ui::Widget *ui;
    QSystemTrayIcon tray;
    void closeEvent(QCloseEvent *event);
    void initTray();
};

#endif // WIDGET_H
#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    setWindowTitle(qApp->applicationDisplayName());
    initTray();
    tray.show();
    tray.showMessage(u8"歡迎",u8"程序已啓動");
}

Widget::~Widget(){
    delete ui;
}

void Widget::closeEvent(QCloseEvent *event){
    event->ignore();
    hide();
}

void Widget::initTray(){
    //先添加一個資源文件,放入 logo
    connect(&tray,&QSystemTrayIcon::activated,this,[&](QSystemTrayIcon::ActivationReason reason){
        switch(reason){
        case QSystemTrayIcon::Trigger:
        case QSystemTrayIcon::DoubleClick:
        case QSystemTrayIcon::MiddleClick:
            if(isHidden()){
                show();
                activateWindow();
            }else hide();
        }
    });
    auto menu = new QMenu(this);
    connect(menu->addAction(u8"退出程序"),&QAction::triggered,this,[&]{
        QMessageBox about(QMessageBox::NoIcon,windowTitle(),u8"<FONT size=4><div><b>您確定要退出程式嗎?</b></div></FONT>",QMessageBox::Ok|QMessageBox::Cancel,this);
        about.setIconPixmap(QPixmap(":/logo.png"));
        if(about.exec()==QMessageBox::Cancel)return;
        qApp->quit();//退出程序
    });
    tray.setContextMenu(menu);
    tray.setToolTip(qApp->applicationDisplayName());
    tray.setIcon(QIcon(":/logo.png"));
}

運行效果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章