QT 自定义最小化到托盘

#include
#include
#include
#include
#include
#include
//#pragma execution_character_set("utf-8");

class assistant : public QWidget
{
    Q_OBJECT

public:
    assistant();
    ~assistant();


public:


    void createActions();
    void createMenu();
    void on_min_clicked();
    void slot_Widget_minimum();
private slots:
    
    void on_activatedSysTrayIcon(QSystemTrayIcon::ActivationReason reason);
    void on_showMainAction();
    void on_exitAppAction();

private:
    //Ui::assistantClass ui;

    QSystemTrayIcon *mSysTrayIcon=nullptr;
    QMenu *mMenu = nullptr;
    QAction *mShowMainAction = nullptr;
    QAction *mExitAppAction = nullptr;
};

#endif // ASSISTANT_H

 

 

#include "assistant.h"

#include

assistant::assistant()

{

 


}

assistant::~assistant()
{

}

 

 


void assistant::on_min_clicked()
{
    //隐藏主窗口
    this->hide();

    //新建QSystemTrayIcon对象
    mSysTrayIcon = new QSystemTrayIcon(this);
    //新建托盘要显示的icon
    QIcon icon = QIcon(":/assistant/Resources/test/question.png");
    //将icon设到QSystemTrayIcon对象中
    mSysTrayIcon->setIcon(icon);
    //当鼠标移动到托盘上的图标时,会显示此处设置的内容
    mSysTrayIcon->setToolTip(QString::fromLocal8Bit("测试系统托盘图标"));
    //给QSystemTrayIcon添加槽函数
    connect(mSysTrayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(on_activatedSysTrayIcon(QSystemTrayIcon::ActivationReason)));

    //建立托盘操作的菜单
    createActions();
    createMenu();
    //在系统托盘显示此对象
    mSysTrayIcon->show();
}

void assistant::slot_Widget_minimum()
{
    if (this->isHidden())
    {
        return;
    }

    if (mSysTrayIcon == NULL)
    {
        on_min_clicked();
    }
    else
    {
        this->hide();

    }
}

void assistant::on_activatedSysTrayIcon(QSystemTrayIcon::ActivationReason reason)
{
    switch (reason) {
    case QSystemTrayIcon::Trigger:
        mSysTrayIcon->showMessage(QObject::trUtf8("Message Title"),
            QString::fromLocal8Bit("欢迎使用导航"),
            QSystemTrayIcon::Information,
            1000);
        break;
    case QSystemTrayIcon::DoubleClick:
        this->show();
        break;
    default:
        break;
    }
}

void assistant::createActions()
{
    mShowMainAction = new QAction(QString::fromLocal8Bit("显示"), this);
    connect(mShowMainAction, SIGNAL(triggered()), this, SLOT(on_showMainAction()));

    mExitAppAction = new QAction(QString::fromLocal8Bit("退出"), this);
    connect(mExitAppAction, SIGNAL(triggered()), this, SLOT(on_exitAppAction()));

}

void assistant::createMenu()
{
    mMenu = new QMenu(this);
    mMenu->addAction(mShowMainAction);

    mMenu->addSeparator();

    mMenu->addAction(mExitAppAction);

    mSysTrayIcon->setContextMenu(mMenu);
}

void assistant::on_showMainAction()
{
    this->show();
}

void assistant::on_exitAppAction()
{
    exit(0);
}
 

 

 

你可能感兴趣的:(QT 自定义最小化到托盘)