Qt实现程序最小化后从任务栏转到右下角托盘,请给我具体代码
时间: 2023-06-19 15:06:20 浏览: 140
以下是实现程序最小化后从任务栏转到右下角托盘的Qt代码:
```cpp
#include <QApplication>
#include <QSystemTrayIcon>
#include <QMenu>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
// 创建系统托盘图标
QSystemTrayIcon* trayIcon = new QSystemTrayIcon;
// 设置托盘图标
trayIcon->setIcon(QIcon(":/images/icon.png"));
// 创建菜单
QMenu* trayIconMenu = new QMenu;
QAction* restoreAction = new QAction("Restore", trayIconMenu);
QAction* quitAction = new QAction("Quit", trayIconMenu);
trayIconMenu->addAction(restoreAction);
trayIconMenu->addAction(quitAction);
// 设置托盘菜单
trayIcon->setContextMenu(trayIconMenu);
// 显示系统托盘图标
trayIcon->show();
// 最小化程序时隐藏主窗口,并显示托盘提示信息
app.setQuitOnLastWindowClosed(false);
QObject::connect(&app, &QGuiApplication::applicationStateChanged, [=](Qt::ApplicationState state) {
if (state == Qt::ApplicationMinimized) {
trayIcon->show();
QApplication::activeWindow()->hide();
}
});
// 点击托盘图标恢复主窗口
QObject::connect(trayIcon, &QSystemTrayIcon::activated, [=](QSystemTrayIcon::ActivationReason reason) {
if (reason == QSystemTrayIcon::Trigger) {
trayIcon->hide();
QApplication::activeWindow()->showNormal();
}
});
// 点击托盘菜单中的 Restore 恢复主窗口
QObject::connect(restoreAction, &QAction::triggered, [=]() {
trayIcon->hide();
QApplication::activeWindow()->showNormal();
});
// 点击托盘菜单中的 Quit 退出程序
QObject::connect(quitAction, &QAction::triggered, [=]() {
trayIcon->hide();
qApp->quit();
});
return app.exec();
}
```
需要注意的是,为了实现最小化时隐藏主窗口并显示系统托盘图标,需要在 `main()` 函数中添加以下代码:
```cpp
// 最小化程序时隐藏主窗口,并显示托盘提示信息
app.setQuitOnLastWindowClosed(false);
QObject::connect(&app, &QGuiApplication::applicationStateChanged, [=](Qt::ApplicationState state) {
if (state == Qt::ApplicationMinimized) {
trayIcon->show();
QApplication::activeWindow()->hide();
}
});
```
另外,为了实现点击托盘图标恢复主窗口,需要在 `main()` 函数中添加以下代码:
```cpp
// 点击托盘图标恢复主窗口
QObject::connect(trayIcon, &QSystemTrayIcon::activated, [=](QSystemTrayIcon::ActivationReason reason) {
if (reason == QSystemTrayIcon::Trigger) {
trayIcon->hide();
QApplication::activeWindow()->showNormal();
}
});
```
此外,为了实现点击托盘菜单中的 Restore 恢复主窗口,需要在 `main()` 函数中添加以下代码:
```cpp
// 点击托盘菜单中的 Restore 恢复主窗口
QObject::connect(restoreAction, &QAction::triggered, [=]() {
trayIcon->hide();
QApplication::activeWindow()->showNormal();
});
```
最后,为了实现点击托盘菜单中的 Quit 退出程序,需要在 `main()` 函数中添加以下代码:
```cpp
// 点击托盘菜单中的 Quit 退出程序
QObject::connect(quitAction, &QAction::triggered, [=]() {
trayIcon->hide();
qApp->quit();
});
```
阅读全文