
对于Qt GUI程序,如果想要实现当最小化时,程序从任务栏消失,在平台托盘显示一个图标,表示此程序,并可在托盘内通过双击或者菜单使程序图标恢复。
其中QSystemTrayIcon是主要操作系统托盘的操作类,通过这种,可以在托盘显示选定程序的界面,响应用户键盘的点击,双击,或wheel操作(好像只对X11系统有用),显示指定消息,显示菜单等。
此类中有两个枚举类型,分别如下:
enum QSystemTrayIcon::ActivationReason 表述托盘上按钮的触发缘由


image.png
enum QSystemTrayIcon::MessageIcon 当显示气球消息时显示的照片

image.png
void setIcon(const QIcon& icon)

设置系统托盘的界面
void setToolTip(const QString &tip)
设置鼠标放在界面上的提示文字
void setContextMenu(QMenu* menu);
设置当单击按钮弹出的菜单

void show()
显示系统托盘图标
最小化后显示在平台托盘内,此时不仅在任务管理器中结束此程序,无法再做其它操作,而我们还想实现双击图标显示主界面qt 最小化到托盘,单击图标弹出菜单等实现其它操作qt 最小化到托盘,此时,就必须使用QSystemTrayIcon::ActivationReason属性了。
1、给QSystemTrayIcon对象添加信号为activated(QSystemTrayIcon::ActivationReason)的槽函数
2、在槽函数内,对双击事件,显示主窗口界面

程序代码:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QSystemTrayIcon>
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QMenu *m = new QMenu(this);
QIcon icon(":/pic/1.ico");
systemTray = new QSystemTrayIcon(this);
systemTray->setIcon(icon);
systemTray->setToolTip("托盘测试");
minimumAct = new QAction("窗口最小化", this);
connect(minimumAct, SIGNAL(triggered()), this, SLOT(hide()));
maximumAct = new QAction("窗口最大化", this);
connect(maximumAct, SIGNAL(triggered()), this, SLOT(showMaximized()));
restoreAct = new QAction("恢复窗口", this);
connect(restoreAct, SIGNAL(triggered()), this, SLOT(showNormal()));
quitAct = new QAction("退出程序", this);
connect(quitAct, SIGNAL(triggered()), qApp, SLOT(quit()));
connect(systemTray,SIGNAL(activated(QSystemTrayIcon::ActivationReason)),this,SLOT(on_activatedSysTrayIcon(QSystemTrayIcon::ActivationReason)));
QMenu *pContextMenu = new QMenu(this);
pContextMenu->addAction(minimumAct);
pContextMenu->addAction(maximumAct);
pContextMenu->addAction(restoreAct);
pContextMenu->addSeparator();
pContextMenu->addAction(quitAct);
systemTray->setContextMenu(pContextMenu);
systemTray->show();
close();
}
void MainWindow::closeEvent(QCloseEvent *event)
{
if(systemTray->isVisible())
{
hide();
systemTray->showMessage("托盘", "该程序托盘正在运行!");
}
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_activatedSysTrayIcon(QSystemTrayIcon::ActivationReason reason)
{
switch(reason){
case QSystemTrayIcon::Trigger:
//单击托盘图标
break;
case QSystemTrayIcon::DoubleClick:
//双击托盘图标
//双击后显示主程序窗口
this->show();
break;
default:
break;
}
}

image.png

image.png
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/tongxinshuyu/article-143559-1.html
故意用一艘老军舰来挑衅中国
0
期待期待