adjusted behavior of system tray icon to persist when the main window is closed. Fixed unguarded ifs which avoids tray icon being created multiple times

This commit is contained in:
gcbritt 2024-08-16 01:46:46 -07:00
parent a05ecb7a09
commit cdde9947c8

View File

@ -104,8 +104,7 @@ MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) {
void MainWindow::setTrayIconEnabled(bool enable) { void MainWindow::setTrayIconEnabled(bool enable) {
if (enable) { if (enable) {
if (!m_trayIcon) if (!m_trayIcon) {
// This seems to make the main window not close during closeEvent
m_trayIcon = new QSystemTrayIcon{this}; m_trayIcon = new QSystemTrayIcon{this};
m_trayIcon->setIcon(QIcon{QPixmap{":/tuxclocker-logo.svg"}}); m_trayIcon->setIcon(QIcon{QPixmap{":/tuxclocker-logo.svg"}});
m_trayIcon->setToolTip("TuxClocker"); m_trayIcon->setToolTip("TuxClocker");
@ -113,18 +112,27 @@ void MainWindow::setTrayIconEnabled(bool enable) {
m_trayIcon->show(); m_trayIcon->show();
return; return;
} }
// Remove tray icon else
if (m_trayIcon) return;
}
if (m_trayIcon) {
delete m_trayIcon; delete m_trayIcon;
m_trayIcon = nullptr;
}
} }
QMenu *MainWindow::createTrayMenu() { QMenu *MainWindow::createTrayMenu() {
auto menu = new QMenu{this}; auto menu = new QMenu{this};
auto show = new QAction{_("&Maximize TuxClocker"), this}; auto show = new QAction{_("&Show TuxClocker"), this};
connect(show, &QAction::triggered, this, &MainWindow::show); connect(show, &QAction::triggered, this, &MainWindow::show);
menu->addAction(show); menu->addAction(show);
auto hide = new QAction{_("&Hide TuxClocker"), this};
connect(hide, &QAction::triggered, this, &MainWindow::hide);
menu->addAction(hide);
auto quit = new QAction{_("&Quit"), this}; auto quit = new QAction{_("&Quit"), this};
connect(quit, &QAction::triggered, this, &QApplication::quit); connect(quit, &QAction::triggered, this, &QApplication::quit);
menu->addAction(quit); menu->addAction(quit);
@ -140,7 +148,21 @@ void MainWindow::restoreGeometryFromCache(QWidget *widget) {
} }
void MainWindow::closeEvent(QCloseEvent *event) { void MainWindow::closeEvent(QCloseEvent *event) {
// if the tray icon is active, hide the application instead of closing it
if (m_trayIcon && m_trayIcon->isVisible()) {
QMessageBox::information(this, tr("TuxClocker"),
tr("TuxClocker will continue to run "
"in the background. To completely "
"exit the application, choose <b><u>Q</u>uit</b> "
"from the system tray icon"));
hide();
event->ignore();
return;
}
// Save window geometry to user cache dir (XDG_CACHE_HOME on Linux) // Save window geometry to user cache dir (XDG_CACHE_HOME on Linux)
auto cacheFilePath = Utils::cacheFilePath(); auto cacheFilePath = Utils::cacheFilePath();
QSettings settings{cacheFilePath, QSettings::NativeFormat}; QSettings settings{cacheFilePath, QSettings::NativeFormat};