参考:
Qt系统托盘程序的实现_qt托盘程序-CSDN博客
QT系统托盘应用程序-CSDN博客文章来源:https://www.toymoban.com/news/detail-818940.html
代码:文章来源地址https://www.toymoban.com/news/detail-818940.html
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QSystemTrayIcon>
#include <QDebug>
#include <QMenu>
#include <QCloseEvent>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
public slots:
void showWindow();
void on_exitAppAction();
void iconActivated(QSystemTrayIcon::ActivationReason reason);
protected:
void closeEvent(QCloseEvent *event);
private:
Ui::Widget *ui;
QSystemTrayIcon *sysTray;
//打开工具
//安全退出
QAction *open;
QAction *exit;
QMenu *contextMenu;
};
#endif // WIDGET_H
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
sysTray=new QSystemTrayIcon(this);
sysTray->setIcon(QIcon(QApplication::applicationDirPath()+"/icon.ico"));
//qDebug()<<QApplication::applicationDirPath()+"/icon.ico";
open=new QAction("打开工具",this);
exit=new QAction("安全退出",this);
connect(open,&QAction::triggered,this,&Widget::showWindow);
connect(exit,&QAction::triggered,this,&Widget::on_exitAppAction);
connect(sysTray,&QSystemTrayIcon::activated,this,&Widget::iconActivated);
contextMenu=new QMenu(this);
contextMenu->addAction(open);
contextMenu->addAction(exit);
sysTray->setContextMenu(contextMenu);
sysTray->show();
this->hide();
}
Widget::~Widget()
{
delete ui;
}
void Widget::showWindow()
{
show();
raise();
}
void Widget::on_exitAppAction()
{
qApp->exit();
}
void Widget::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
switch (reason) {
case QSystemTrayIcon::Trigger:
showWindow();
break;
default:
break;
}
}
void Widget::closeEvent(QCloseEvent *event)
{
this->hide();
event->ignore();
}
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
到了这里,关于Qt系统托盘的学习的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!