Solved qwidget reports incorrect width value
-
i have such a class
class MyWidget : public QWidget { /// ... };
then i add widgets to a hbox layout, and set thay layout to
MyWidget
object.
i wantMyWidget
widget to have the width of a widget contained in it.
so i overrode size hint:QSize MyWidget::sizeHint() const { // use the width of the first widget in the frame if (auto pLayout = layout()) { auto pItem = pLayout->itemAt(0); //std::cout << pItem->widget()->width() << std::endl; if (pItem && pItem->widget()) return QSize{ pItem->widget()->width(), QWidget::sizeHint().height() }; } return QWidget::sizeHint(); }
now,
pItem->widget()->width()
always reports the same value no matter what size the widget is. what's the problem??? -
@user4592357
Hi
If you call pItem->widget()->width() while the inner widget
is not visible, it might not report actual size. ( layout are not calculated yet )
You can try use the ShowEvent instead or
use
layout->invalidate();
layout->activate();
to try to force layout to be calculated before shown. -
this didn't work, i get the same result:
QSize MyWidget::sizeHint() const { // use the width of the first widget in the frame if (auto pLayout = layout()) { auto pItem = pLayout->itemAt(0); //std::cout << pItem->widget()->sizeHint().width() << std::endl; if (pItem && pItem->widget()) { pLayout->invalidate(); pLayout->activate(); return QSize{ pItem->widget()->width(), QWidget::sizeHint().height() }; } } return QWidget::sizeHint(); }
and i don't get how i'd use the inner widget sizes in
showEvent()
-
Hi
Hmm ok. I did something similar and that worked but i cant spot the difference.
Well try
pItem->widget()->width()
in ShowEvent to see if that even report expected size.Also if MyWidget is a layout, then layout set size of it.
Unless you set MinimumSize for MyWidget
It will ignore resize / set Geometry.
Also sizeHint is just suggested size but if innner widget is also in a layout, then
om not sure this logic can even work. ( as inner widget then follow outer widget)
So something about this setup confuses me. -
yes, inner widget has min size set
and inshowEvent
inner widget still has the same size as before. -
@user4592357
So it does not report the minimumSize for the inner widget? -
no, it reports a little big larger, like 12px larger.
also, i have setsetSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
p.s. i solved this another way. thanks for helping