Qt点击关闭窗口按钮隐藏窗口并在任务栏生成程序图标
时间: 2024-02-27 17:56:10 浏览: 182
可以通过重载QWidget的closeEvent()函数来实现点击关闭窗口按钮隐藏窗口,并在任务栏生成程序图标的功能。具体实现方法如下:
1. 在窗口类的头文件中添加以下代码:
```
protected:
void closeEvent(QCloseEvent *event);
```
2. 在窗口类的源文件中重载closeEvent()函数,添加以下代码:
```
void YourMainWindow::closeEvent(QCloseEvent *event)
{
// 隐藏窗口
hide();
// 取消关闭事件
event->ignore();
}
```
3. 在窗口类的构造函数中添加以下代码:
```
// 设置窗口关闭按钮为隐藏
setAttribute(Qt::WA_DeleteOnClose, false);
setWindowFlags(windowFlags() | Qt::WindowMinimizeButtonHint | Qt::WindowSystemMenuHint);
```
4. 在mainwindow.cpp中添加以下代码,实现任务栏图标:
```
#include <QSystemTrayIcon>
// 创建系统托盘图标
QSystemTrayIcon* trayIcon = new QSystemTrayIcon(this);
trayIcon->setIcon(QIcon(":/icon.png"));
trayIcon->setToolTip("Your Application");
trayIcon->show();
// 点击系统托盘图标时显示窗口
connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(showNormal()));
```
其中,":/icon.png"是任务栏图标的路径。你可以将其替换为自己的图标路径。最后,记得在.pro文件中添加以下代码,以支持系统托盘图标:
```
QT += widgets
```
这样,当用户点击关闭窗口按钮时,窗口将被隐藏,并在任务栏生成程序图标。用户可以通过点击程序图标重新打开窗口。
阅读全文
相关推荐
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![7z](https://img-home.csdnimg.cn/images/20241231044736.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)