LuisABOL
LuisABOL

Reputation: 2991

Reshowing maximized QWidget

I'm facing a problem when running Qt applications. Consider the following code snippet.

#include <QApplication>
#include <QLabel>
#include <QPushButton>
#include <QVBoxLayout>
#include <QWidget>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QWidget mainWindow;
    mainWindow.setMinimumWidth(400);
    mainWindow.setWindowTitle("Main window");
    QVBoxLayout *layout1 = new QVBoxLayout(&mainWindow);
    QPushButton *pushButton = new QPushButton("Click to open aux window");
    layout1->addWidget(pushButton);

    QWidget *auxWindow = new QWidget(&mainWindow, Qt::Window);
    auxWindow->setMinimumWidth(400);
    auxWindow->setWindowTitle("Aux window");
    QVBoxLayout *layout2 = new QVBoxLayout(auxWindow);
    QLabel *label = new QLabel("This is aux window");
    layout2->addWidget(label);

    QObject::connect(pushButton, &QPushButton::clicked, auxWindow, &QWidget::show);

    mainWindow.show();

    return a.exec();
}

This code creates a window (main window) in which there is a push button. This push button, when clicked, shows another window (aux window). If the user had previously closed aux window, pushing main window's push button causes aux window to reopen.

I need aux window to reopen in the maximization state it had before being closed, and it seems Qt does it automatically, so that if the user closes the window maximized, it is reshown maximized.

The problem is aux window is not painted properly when reshown maximized. Aux window is reopened with the correct maximized size, but its contents are displayed as if it had its default unmaximized size.

Aux window maximized before being closed for the first time.

Aux window maximized after being closed for the first time and reshown.

I know I could use QWidget::showMaximized() if I wanted aux window to reopen maximized, but, again, I need aux window to restore its previous maximization state, which is not always maximized.

So, what is the correct way to have a maximized reshown window painted properly?

I'm using Qt 5.9.3 on Windows 10.

Upvotes: 2

Views: 637

Answers (1)

It's a Qt bug, and the workaround is to force a relayout of the window via a delayed QWidget::updateGeometry. The window has the correct state, but the layout doesn't get the message, so to speak.

class MyWidget : public QWidget {
  Q_OBJECT
  using self = MyWidget;
  using base_class = QWidget;
  //...
protected:
  void showEvent(QShowEvent *ev) override {
    QTimer::singleShot(0, this, [this]{
      qDebug() << geometry();
      updateGeometry();
    });
    base_class::showEvent(ev);
  }
};

Upvotes: 2

Related Questions