Qt在系统托盘中为应用程序提供图标。

主要用到 QSystemTrayIcon 

头文件中增加如下代码,

//QSystemTrayIcon任务栏托盘菜单
private:
    QSystemTrayIcon *myTrayIcon;
    QMenu *myMenu;
    QAction *restoreWinAction;
    QAction *quitAction;
    void createMenu();
private slots:
    void showNormalSlot();

源文件代码:

void MainWindow::createMenu()
{    
    restoreWinAction = new QAction("recover(&R)",this);    
    quitAction = new QAction("quit(&Q)",this);    
    //恢复   
    connect(restoreWinAction,SIGNAL(triggered()),this,SLOT(showNormalSlot()));    
    //退出    
    connect(quitAction,SIGNAL(triggered()),qApp,SLOT(quit()));    
    myMenu = new QMenu((QWidget*)QApplication::desktop());   
    //添加菜单    
    myMenu->addAction(restoreWinAction);    
    //分隔符    
    myMenu->addSeparator();    
    myMenu->addAction(quitAction);
}

构造函数中添加如下代码:

    //QSystemTrayIcon任务栏托盘菜单    
    //菜单    
    createMenu();    
    //判断系统是否支持托盘图标    
    if(!QSystemTrayIcon::isSystemTrayAvailable())    
    {    
        return;    
    }
    //实例 QSystemTrayIcon
    myTrayIcon = new QSystemTrayIcon(this);
    //设置图标
    myTrayIcon->setIcon(QIcon(":/pic/sun"));
    //鼠标放托盘图标上提示信息
    myTrayIcon->setToolTip("Qt Tray icon function");
    //设置消息
    myTrayIcon->showMessage("Tray","TrayManager",QSystemTrayIcon::Information,10000);
    //托盘菜单
    myTrayIcon->setContextMenu(myMenu);
    //显示
    myTrayIcon->show();

//点击最小化按钮隐藏界面
void QWidget::changeEvent(QEvent *e)
{
    if((e->type()==QEvent::WindowStateChange)&&this->isMinimized())
    {
        //QTimer::singleShot(100, this, SLOT(hide()));
        this->hide();
    }
}

 

你可能感兴趣的:(Qt在系统托盘中为应用程序提供图标。)