Qt系统托盘的学习

发布时间:2024年01月22日

参考:

Qt系统托盘程序的实现_qt托盘程序-CSDN博客

QT系统托盘应用程序-CSDN博客

代码:

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QSystemTrayIcon>
#include <QDebug>
#include <QMenu>
#include <QCloseEvent>
namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();
public slots:
    void showWindow();
    void on_exitAppAction();
    void iconActivated(QSystemTrayIcon::ActivationReason reason);
protected:
    void closeEvent(QCloseEvent *event);
private:
    Ui::Widget *ui;
    QSystemTrayIcon *sysTray;
    //打开工具
    //安全退出
    QAction *open;
    QAction *exit;

    QMenu *contextMenu;
};

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

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    sysTray=new QSystemTrayIcon(this);
    sysTray->setIcon(QIcon(QApplication::applicationDirPath()+"/icon.ico"));
    //qDebug()<<QApplication::applicationDirPath()+"/icon.ico";

    open=new QAction("打开工具",this);
    exit=new QAction("安全退出",this);
    connect(open,&QAction::triggered,this,&Widget::showWindow);
    connect(exit,&QAction::triggered,this,&Widget::on_exitAppAction);
    connect(sysTray,&QSystemTrayIcon::activated,this,&Widget::iconActivated);
    contextMenu=new QMenu(this);
    contextMenu->addAction(open);
    contextMenu->addAction(exit);
    sysTray->setContextMenu(contextMenu);
    sysTray->show();
    this->hide();
}

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

void Widget::showWindow()
{
    show();
    raise();
}

void Widget::on_exitAppAction()
{
    qApp->exit();
}

void Widget::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
    switch (reason) {
    case QSystemTrayIcon::Trigger:
        showWindow();
        break;
    default:
        break;
    }
}

void Widget::closeEvent(QCloseEvent *event)
{
    this->hide();
    event->ignore();
}
#include "widget.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();
    return a.exec();
}

文章来源:https://blog.csdn.net/weixin_51883798/article/details/135755500
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。