Qt5 任务栏托盘功能实现
23333 有一阵子没写博客了,研究了挺长时间qt,学到任务栏托盘时简直无语,网上找得到的代码大多是废码,Qt5不支持或者本身就有毛病不能实现却被n多人转来转去的,甚是无语。
简单托盘功能以下在Qt5.5编译通过:
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QSystemTrayIcon>//任务栏类 #include <QMenu>//菜单类 namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private: QSystemTrayIcon *myTrayIcon; QMenu *myMenu; QAction *restoreWinAction; QAction *quitAction; void createMenu(); Ui::MainWindow *ui; private slots: void showNormal(); }; #endif // MAINWINDOW_H
#include "mainwindow.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); }
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); //菜单 createMenu(); //判断系统是否支持托盘图标 if(!QSystemTrayIcon::isSystemTrayAvailable()) { return; } //实例QSystemTrayIcon myTrayIcon = new QSystemTrayIcon(this); //设置图标 myTrayIcon->setIcon(QIcon(":/new/prefix1/abc")); //鼠标放托盘图标上提示信息 myTrayIcon->setToolTip("Qt托盘图标功能"); //设置消息 myTrayIcon->showMessage("托盘","托盘管理",QSystemTrayIcon::Information,10000); //托盘菜单 myTrayIcon->setContextMenu(myMenu); //显示 myTrayIcon->show(); } //绘制菜单 void MainWindow::createMenu() { restoreWinAction = new QAction("恢复(&R)",this); quitAction = new QAction("退出(&Q)",this); //恢复 connect(restoreWinAction,SIGNAL(triggered()),this,SLOT(showNormal())); //退出 connect(quitAction,SIGNAL(triggered()),qApp,SLOT(quit())); myMenu = new QMenu((QWidget*)QApplication::desktop()); //添加菜单 myMenu->addAction(restoreWinAction); //分隔符 myMenu->addSeparator(); myMenu->addAction(quitAction); } //恢复 void MainWindow::showNormal() { this->show(); } //点击最小化按钮隐藏 void QWidget::changeEvent(QEvent *e) { if((e->type()==QEvent::WindowStateChange)&&this->isMinimized()) { this->hide(); } } MainWindow::~MainWindow() { delete ui; }
PS:
RC_FILE = 1.rc
PS:
1.rc
IDI_ICON1 ICON "6.ico"
所需图片要写在rc配置文件或者添加到工程资源中,.cto文件自备2333。