Fatemeh Karimi
Fatemeh Karimi

Reputation: 987

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().

Upvotes: 2

Views: 1584

Answers (2)

Ye.Feng
Ye.Feng

Reputation: 849

You can implement your own widget inherited from QWiget, and reimplements QWidget's function showEvent(QShowEvent*) and resizeEvent(QResizeEvent*),and you can get true label's height in these function.

Upvotes: 1

m7913d
m7913d

Reputation: 11064

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();
...

Upvotes: 3

Related Questions