Not able to connect aboutToQuit signal from QApplication

2.2k Views Asked by At

I have a Qt Application which i want to show in the System Tray. My desired behavior is that if the user clicks the close button of the Application than that application hides in the system tray but does not exit.

My code in main.cpp is :

 if (QSystemTrayIcon::isSystemTrayAvailable())
  {
    QObject *root = engine.rootObjects().at(0);
    QQuickWindow *window = qobject_cast<QQuickWindow *>(root);
    QAction *showAction = new QAction(QObject::tr("Show"), window);
    window->connect(showAction, SIGNAL(triggered()), window, SLOT(show()));
    QAction *hideAction = new QAction(QObject::tr("Hide"), window);
    window->connect(hideAction, SIGNAL(triggered()), window, SLOT(hide()));
    QAction *quitAction = new QAction(QObject::tr("&Quit"), window);
    window->connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
    QObject::connect(qApp,SIGNAL(aboutToQuit()),window,SLOT(hide()));

    QMenu *trayIconMenu = new QMenu();
    trayIconMenu->addAction(showAction);
    trayIconMenu->addAction(hideAction);
    trayIconMenu->addSeparator();
    trayIconMenu->addAction(quitAction);

    QSystemTrayIcon *trayIcon = new QSystemTrayIcon(window);
    trayIcon->setContextMenu(trayIconMenu);
    trayIcon->setToolTip("xxx");
    trayIcon->setIcon(QIcon("xxx.png"));
    trayIcon->show();
   }

Now i am not able to connect the aboutToQuit signal and hide the application in the tray i.e QObject::connect(qApp,SIGNAL(aboutToQuit()),window,SLOT(hide())); line is not correct but i am not getting any errors etc. Apart from this everything is working correctly.Can someone please tell me what i am doing wrong and how can i achieve my desired behavior. I would also like to know whether i have got the right signal to connect or whether i should try connecting to some other signal. Thanks in advance.

1

There are 1 best solutions below

1
On

You can use :

qApp()->setQuitOnLastWindowClosed(false);

quitOnLastWindowClosed property is true by default which causes your application to quit when the last window is closed. By setting it to false, your application does not terminate when you close the main window.

You can also reimplement closeEvent of your main widget, ignore the close event and just hide your window :

void MainWindow::closeEvent(QCloseEvent * e)
{
    e->ignore();
    this->hide();
}