Search code examples
c++qtqt5qwidget

How to find the true height of a QWidget inside a layout with Qt expanding policy?


My Qt program has a window, and inside the window, there is a QVBoxLayout layout. I added a QLabel to the layout with the Qt::Expanding size policy. here is the code.

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QWidget* window = new QWidget();
    QVBoxLayout* main_layout = new QVBoxLayout(window);
    QLabel* label = new QLabel();
    label->setStyleSheet("background-color: blue");
    label->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    main_layout->addWidget(label);
    window->resize(700, 700);
    qDebug() << "height = " << label->height() << " width = " << label->width();
    window->show();
    return app.exec();
}

I want to have the true size QLabel in the window, so I can calculate a font size for it. but when I try to get the size with QLabel::height(), it always gives me the same number no matter what the window size is. for example, when the window size is (700, 700) it gives height = 480 width = 640. when I set the window size to (1000, 1000) it prints the same. how can I get the true value of the QLabel?

I also tested sizeHint, which acted like height().


Solution

  • The problem is that QWidget::resize doesn't resize your widget immediately if the widget is hidden:

    If the widget is visible when it is being resized, it receives a resize event (resizeEvent()) immediately. If the widget is not currently visible, it is guaranteed to receive an event before it is shown.

    So, when the widget is still hidden, QLabel::height() still returns its initial value, i.e. QLabel::sizeHint().

    Checking QLabel::height() after calling window->show() should resolve your issue:

    ...
    window->show();
    qDebug() << "height = " << label->height() << " width = " << label->width();
    ...