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.
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);
}
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 of0
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With