一.环境
二.源码
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要以管理员身份运行