QT 系统托盘程序,默认以管理员身份运行

一.环境

Qt 5.15.2
图标网站
icon转换

二.源码

1.Qt 项目中新建如下文件:

QT_AdminIcon.rc, QT_AdminIcon.exe.manifest, logo.ico

在这里插入图片描述
在这里插入图片描述

QT_AdminIcon.rc :

1 24 QT_AdminIcon.exe.manifest
IDI_ICON1 ICON DISCARDABLE "logo.ico"

QT_AdminIcon.exe.manifest:

<?xml version='1.0' encoding='UTF-8' standalone='yes'?>  
<assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'>  
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">  
    <security>  
      <requestedPrivileges>  
        <requestedExecutionLevel level='requireAdministrator' uiAccess='false' />  
      </requestedPrivileges>  
    </security>  
  </trustInfo>  
</assembly>

2.Qt Pro 文件中添加:

RC_FILE = QT_AdminIcon.rc

3.Qt 编译运行:

在这里插入图片描述
4.mainwindow.h

class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();
private:
    Ui::MainWindow *ui;
private:
    QSystemTrayIcon tSysTrayIcon;
private slots:
    void slot_activated(QSystemTrayIcon::ActivationReason reason);
protected:
    void closeEvent(QCloseEvent *event);
};
#endif // MAINWINDOW_H

5.mainwindow.cpp

MainWindow::MainWindow(QWidget *parent)
{
    ui->setupUi(this);

    QIcon ico(":/logo.png");
    tSysTrayIcon.setIcon(ico);
    tSysTrayIcon.setToolTip(this->windowTitle());
    connect(&tSysTrayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
            this, SLOT(slot_activated(QSystemTrayIcon::ActivationReason)));

    tSysTrayIcon.hide();
}


void MainWindow::slot_activated(QSystemTrayIcon::ActivationReason reason)
{
    switch (reason)
    {
    case QSystemTrayIcon::DoubleClick:
    {
        this->show();
        tSysTrayIcon.hide();
    }break;
    case QSystemTrayIcon::Context:
    {
        // QMenu *menu = new QMenu(this);
        // menu->addAction(tr("St"), this, SLOT(StFunction()));
        // menu->addAction(tr("Ed"), this, SLOT(EdFunction()));
        // menu->exec(QCursor::pos());
        // delete menu;
    }break;
    default:break;
    }
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    if (QMessageBox::question(this, "关闭", "是否隐藏软件?", QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes)
    {
        tSysTrayIcon.show();
        event->ignore();
        this->hide();
    }else{
        event->accept();
    }
}

三.运行

注意:Qt Creator要以管理员身份运行
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值