5

I'm using Qt and I want my program to be able to go in the system tray, but also to be displayed as a window.

For example: I launch my program, it opens a window, ..., I close the window but the program doesn't close, it is still in the background. Then I can reopen the window through the icon created in the system tray.

I know how to create the icon using QSystemTrayIcon and to create a menu when right-clicking on the icon, and launch events through the menu. Yet I don't know how to do so that when I close my program's window, the program remains opened in the background.

To illustrate my point, it would be the same functionment as Steam.

  • Possible duplicate of [How do I properly implement a "minimize to tray" function in Qt?](http://stackoverflow.com/questions/3332257/how-do-i-properly-implement-a-minimize-to-tray-function-in-qt) – Torbjörn Aug 15 '16 at 11:20
  • @Torbjörn it's not an exact duplicate as "minimizing" and "closing" need to be handled slightly differently – m.s. Aug 15 '16 at 11:21
  • @m.s. I see. Then, sorry for the noise. – Torbjörn Aug 15 '16 at 11:22

1 Answers1

5

You need to reimplement QWidget::closeEvent, hide the window and ignore the QCloseEvent.

This is explained in detail in the Qt System Tray Icon Example, here is the most interesting part:

void Window::closeEvent(QCloseEvent *event)
{
    if (trayIcon->isVisible()) {
        hide();
        event->ignore();
    }
}
m.s.
  • 16,063
  • 7
  • 53
  • 88
  • The problem is that when I call the hide method from my MainWindow class it doesn't hide the window even if I call it using `this` ; it only works if I call hide from the main function where I can't really get the event –  Aug 15 '16 at 11:32
  • @Urefeu you should ask a new question containing a [mcve] – m.s. Aug 15 '16 at 11:34
  • I will, I can't try the solution right now. Besides, when I call `hide()`, it doesn't remove the icon of the program from the taskbar, does it? –  Aug 15 '16 at 11:35
  • @Urefeu you might also try this: http://stackoverflow.com/a/6094872/678093 – m.s. Aug 15 '16 at 11:35
  • @Urefeu regarding the taskbar have a look at http://stackoverflow.com/a/4056292/678093 – m.s. Aug 15 '16 at 11:37