I have a QMainWindow
that minimizes to the tray. In the tray I have two right mouse click menus. Show/Hide and Exit.
When the window is visible and I click to exit menu, the application closes correctly.
When the windows is not visible (hide), the application remains open.
The problem is not in the MainWindow::CloseEvent()
. According to information from the debugger - the application correctly enters the closeEvent
function, but it won't end.
Am I doing something wrong, is this a feature or a bug?
I tried putting this->show()
first before exiting, but it had no effect on the result.
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
...
/* try icon */
trayIcon = new QSystemTrayIcon(this);
trayIcon->setIcon(this->style()->standardIcon(QStyle::SP_ComputerIcon));
trayIcon->setToolTip("Tray Program.\nWorking with minimizing the tray program.");
menu = new QMenu(this);
viewWindow = new QAction(("Maximize window"), this);
quitAction = new QAction(("Exit"), this);
connect(viewWindow, SIGNAL(triggered()), this, SLOT(show()));
connect(quitAction, SIGNAL(triggered()), this, SLOT(closeFromTray()));
closedFromTray = false;
menu->addAction(viewWindow);
menu->addAction(quitAction);
trayIcon->setContextMenu(menu);
trayIcon->show();
connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
...
}
void MainWindow::closeEvent(QCloseEvent * event)
{
if(!closedFromTray)
{
this->hide();
event->ignore();
}
else
{
event->accept();
}
QMainWindow::closeEvent(event);
}
void MainWindow::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
switch (reason)
{
case QSystemTrayIcon::Trigger:
if(!this->isVisible())
{
this->show();
}
else
{
this->hide();
}
break;
default:
break;
}
}
void MainWindow::closeFromTray()
{
closedFromTray = true;
close();
}
How to terminate the application even when the window is hidden?
From QGuiApplication::quitOnLastWindowClosed with my emphasis:
If this property is true, the applications quits when the last visible primary window (i.e. top level window with no transient parent) is closed.". .
Use qApp->quit();
instead of close();
.