# QtTrayMinimize
**Repository Path**: scenario-samples/qt-tray-minimize
## Basic Information
- **Project Name**: QtTrayMinimize
- **Description**: 将“关闭窗口”操作的行为从“退出程序”改为“隐藏到系统托盘”的场景是高频使用场景之一,如即时通讯软件用户点击窗口的“X”时,并非想退出登录、断开连接,而是希望程序在后台保持在线状态,以便持续接收消息、通知,并能在需要时快速点击托盘图标恢复窗口。
- **Primary Language**: Unknown
- **License**: Not specified
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 0
- **Forks**: 1
- **Created**: 2026-01-16
- **Last Updated**: 2026-02-26
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
# HarmonyOS PC中Qt实现应用缩小到系统托盘示例
## 场景介绍
将“关闭窗口”操作的行为从“退出程序”改为“隐藏到系统托盘”的场景是高频使用场景之一,如即时通讯软件用户点击窗口的“X”时,并非想退出登录、断开连接,而是希望程序在后台保持在线状态,以便持续接收消息、通知,并能在需要时快速点击托盘图标恢复窗口。
本示例使用[@ohos.notificationManager(通知管理能力)](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-notificationmanager#notificationmanagerrequestenablenotification10-1)实现将消息推送到通知栏。通过Qt的重写closeEvent回调函数和QSystemTrayIcon的能力实现将“关闭窗口”行为改为“隐藏到系统托盘”。
## 效果预览
## 实现思路
1. 申请用户授权通知权限:
```js
notificationManager.requestEnableNotification(this.context).then(() => {
hilog.info(0x0000, 'testTag', `[ANS] requestEnableNotification success`);
}).catch((err: BusinessError) => {
hilog.error(0x0000, 'testTag', `[ANS] requestEnableNotification failed, code is ${err.code}, message is ${err.message}`);
});
```
2. 在Qt层中重写关闭事件:默认隐藏到托盘,而非退出程序:
```C++
void MainWindow::closeEvent(QCloseEvent *event)
{
qDebug() << "testaaaa in the closeEvent";
if (QSystemTrayIcon::isSystemTrayAvailable()) {
qDebug() << "testaaaa isSystemTrayAvailable";
// 隐藏窗口到托盘
hide();
// 提示用户
QSystemTrayIcon *tray = qApp->property("systemTray").value();
if (tray) {
tray->showMessage("提示", "程序已最小化到托盘", QSystemTrayIcon::Information, 2000);
}
event->ignore(); // 忽略关闭事件
} else {
event->accept(); // 无托盘支持时正常退出
}
}
```
3. Qt层中创建菜单并绑定动作事件:
```C++
// 初始化托盘图标
trayIcon = new QSystemTrayIcon(this);
// 创建托盘右键菜单
trayMenu = new QMenu(this);
// 创建菜单动作
showInfoMsgAction = new QAction("显示信息消息", trayMenu);
showInfoMsgAction->setIcon(qApp->style()->standardIcon(QStyle::SP_MessageBoxInformation));
// 添加动作到菜单
trayMenu->addAction(showInfoMsgAction);
// 关联菜单到托盘
trayIcon->setContextMenu(trayMenu);
// 信号槽关联
connect(showInfoMsgAction, &QAction::triggered, this, &MainWindow::onShowInfoMsg);
```
4. 在槽函数中,通过`showMessage`发送通知到状态栏:
```C++
void MainWindow::onShowInfoMsg() {
trayIcon->showMessage("信息提示", "这是一条信息类气泡消息\n支持换行显示",
QSystemTrayIcon::Information, 3000);
}
```
## 说明
1. 需要将本地Qt安装路径`\plugins\platforms`目录下的`libplugins_platforms_qopenharmony.so`放到`entry/libs/arm64-v8a`中。

2. 开源Qt安装路径配置到`QT_PREFIX`中,可以选择下面两个方案中的一个:
- 修改`\entry\src\main\cpp\TrayIcon\CMakeLists.txt`中的`set(QT_PREFIX "D:\\arkTSProject\\QtSdkOpen\\ohos17_arm64-v8a_release")`为编译出的Qt产物目录:
```txt
# 检查环境变量是否存在
if(DEFINED ENV{WORKSPACE})
set(QT_PREFIX $ENV{WORKSPACE}/code/SDK/Qt/QtOpenSDK)
message(STATUS "get QT_PREFIX PATH: ${QT_PREFIX}")
else()
set(QT_PREFIX "D:\\arkTSProject\\QtSdkOpen\\ohos17_arm64-v8a_release")
message(STATUS "WORKSPACE not defined, using default path: ${QT_PREFIX}")
endif()
```
- 或者删除`entry\src\main\cpp\qtModule\CMakeLists.txt`中的`QT_PREFIX`定义,在`entry\build-profile.json5`中设置`QT_PREFIX`:
```json
"buildOption": {
"externalNativeOptions": {
"path": "./src/main/cpp/CMakeLists.txt",
"arguments": "-DQT_PREFIX=D:\\arkTSProject\\QtSdkOpen\\ohos17_arm64-v8a_release",
"cppFlags": "",
"abiFilters": ["arm64-v8a"]
}
},
```
## 约束与限制
例如:
* 本示例支持API Version 20 Release及以上版本。
* 本示例支持HarmonyOS 6.0.0 Release SDK及以上版本。
* 本示例需要使用DevEco Studio 6.0.0 Release及以上版本进行编译运行。
## 权限说明
获取用户授权发送通知:[notificationManager.requestEnableNotification](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-notificationmanager#notificationmanagerrequestenablenotification10-1)。
## 工程目录
```
├─libs/arm64-v8a // libplugins_platforms_qopenharmony.so等依赖
├─entry/src
│ └─main
│ ├─cpp
│ │ ├─TrayIcon
│ │ │ ├─CMakeLists.txt // Qt模块层CMakelist
│ │ │ ├─main.cpp // Qt层入口
│ │ │ ├─mainwindow.cpp // 实现隐藏到系统托盘
│ │ │ └─mainwindow.h
│ │ ├─types/libentry
│ │ │ └─Index.d.ts
│ │ ├─CMakeLists.txt // Native层CMakelist
│ │ └─napi_init.cpp
│ └─ets
│ ├──entryability
│ │ └──EntryAbility.ets
│ ├──entrybackupablility
│ │ └──EntryBackupAbility.ets
│ └──pages
│ └──Index.ets // 主页面
└─entry/src/main/resources // 应用资源目录
```
## 参考文档
[开源版Qt](https://gitcode.com/qtforohos/Build)
[QSystemTrayIcon](https://doc.qt.io/archives/qt-5.15/qsystemtrayicon.html)