How to get a real size of the widget that has stretch in a layout
-
Hello all! I'm new in QT and yesterday and I had one problem with Stretch. I have a layout with several QLabel, for each of which I set a stretch. One of these QLabels can have a long text that accordinately can take up a QLabel space and expanding it. Therefore I tried to found out a text width QLabel will has by QFontMetrics.horizontalAdvance() and get a QLabel width without text, but with stretch, then if the text width is greater than the QLabel width I want to make shorter this text.
This is what the code below does:
QHBoxLayout *hLayout = new QHBoxLayout; QLabel *firstQLabel = new QLabel; QLabel *secondQLabel = new QLabel; QLabel *thirdQLabel = new QLabel; hLayout->setStretch(0, 1); hLayout->setStretch(1, 1); hLayout->setStretch(2, 4); QFont font("roboto", 11); QString secondQLabelText = "a long text example................................." QFontMetrics fm(font); int secondQLabelWidth = fm.horizontalAdvance(secondQLabelText); if (secondQLabelWidth >= (secondQLabel->width())) { secondQLabel->setText("MORE"); } else secondQLabel->setText(secondQLabelText);
The main problem is that a stretch QLabel has does not change a QLabel width, and when I call QLabel.width(), it every time return 10; I just need to retrieve size of widget that has a stretch
I will be very grateful to anyone who can help me.
-
@Damned-Ananas said in How to get a real size of the widget that has stretch in a layout:
The main problem is that a stretch QLabel has does not change a QLabel width, and when I call QLabel.width(), it every time return 10;
It may indeed be that
width()
does not change due to layout, I don't know and haven't looked. However, widgets do not have a correct width, height etc. until they are shown, at which stage layouts must be acted on and perhaps change the width you can retrieve. The question is where did you read the label's width? You need to do so during (or after), say, the widget'sshowEvent()
(overridable method for a subclassed widget, if you don't want to subclass you can use an event filter). Try that, at least in test, to see whether that delivers a better result for width etc. -
The code you show does not work as the three
QLabels
are not part of any layout.
So settinghLayout->setStretch(0, 1); hLayout->setStretch(1, 1); hLayout->setStretch(2, 4);
does not affect the labels, unless you are doing something else which you did not show.
And, as @JonB said above, until the layouts are applied and the widget is shown, you can't trust the widget's geometry you receive from
geometry()
,width()
orheight()
as these values are generic/default values based on your settings and not how the widget actually looks when being rendered in some window or parent widget.So please show your complete/actual code (and/or try what @JonB suggested)