Qt系统托盘的学习

参考:

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

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

代码:

#ifndef WIDGET_H
#define WIDGET_H

#include 
#include 
#include 
#include 
#include 
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()<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 

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

你可能感兴趣的:(qt,学习,开发语言)