Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 540
Jake Petroules Avatar asked Jul 26 '10 04:07

Jake Petroules


2 Answers

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);
}
like image 168
Jake Petroules Avatar answered Oct 05 '22 11:10

Jake Petroules


In addition to what Jake Petroules said, it appears that simply doing:

QTimer::singleShot(0, this, SLOT(hide()));

is enough. From http://qt-project.org/doc/qt-4.8/qtimer.html#details :

As a special case, a QTimer with a timeout of 0 will time out as soon as all the events in the window system's event queue have been processed.

This way you don't have the problem of selecting an appropriate delay value...

like image 39
Manjabes Avatar answered Oct 05 '22 09:10

Manjabes