Jake Petroules Jake Petroules - 3 months ago 40
C++ Question

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

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 simply minimizes to the taskbar and the client area appears blank white when restored.

if (Preferences::instance().minimizeToTray())
{
e->ignore();
this->setVisible(false);
}


Attempting to ignore the event doesn't seem to do anything, either.

Answer

Apparently a small delay is needed to process other events (perhaps someone will post the exact details?). Here's what I ended up doing, which works perfectly:

void MainWindow::changeEvent(QEvent* e)
{
    switch (e->type())
    {
        case QEvent::LanguageChange:
            this->ui->retranslateUi(this);
            break;
        case QEvent::WindowStateChange:
            {
                if (this->windowState() & Qt::WindowMinimized)
                {
                    if (Preferences::instance().minimizeToTray())
                    {
                        QTimer::singleShot(250, this, SLOT(hide()));
                    }
                }

                break;
            }
        default:
            break;
    }

    QMainWindow::changeEvent(e);
}