How do I properly implement a “minimize to tray” function in Qt?

后端 未结 4 1620
抹茶落季
抹茶落季 2020-12-08 11:36

How do I properly implement a \"minimize to tray\" function in Qt?

I tried the following code inside QMainWindow::changeEvent(QEvent *e), but the window

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-08 12:02

     void main_window::create_tray_icon()
     {
        m_tray_icon = new QSystemTrayIcon(QIcon(":/icon.png"), this);
    
        connect( m_tray_icon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(on_show_hide(QSystemTrayIcon::ActivationReason)) );
    
        QAction *quit_action = new QAction( "Exit", m_tray_icon );
        connect( quit_action, SIGNAL(triggered()), this, SLOT(on_exit()) );
    
        QAction *hide_action = new QAction( "Show/Hide", m_tray_icon );
        connect( hide_action, SIGNAL(triggered()), this, SLOT(on_show_hide()) );
    
        QMenu *tray_icon_menu = new QMenu;
        tray_icon_menu->addAction( hide_action );
        tray_icon_menu->addAction( quit_action );
    
        m_tray_icon->setContextMenu( tray_icon_menu );
    
        m_tray_icon->show();
      }
    
    void main_window::on_show_hide( QSystemTrayIcon::ActivationReason reason )
    {
        if( reason )
        {
            if( reason != QSystemTrayIcon::DoubleClick )
            return;
        }
    
        if( isVisible() )
        {
            hide();
        }
        else
        {
            show();
            raise();
            setFocus();
        }
    }
    

    That's how I realize a "minimize to tray". You can now minimize either by double clicking on the icon, or by right-clicking and selecting "Show/Hide" in the menu.

提交回复
热议问题