3

I'm using a QListWidget that is populated with instances of my own custom menu item widget. The menu item widget consists of a QWidget with a QHBoxLayout, and several QLabels.

I am happy with everything, except that the QHBoxLayout seems to take over the size of my widget, shrinking my widget height so that it fits the labels contained within. I want the menu item widget to be a constant size, and just have the QHBoxLayout arrange its children horizontally, and it's driving me crazy that it takes over the height of the widget!

Does anyone have any ideas? I've tried things in my menu item QWidget like:

this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
this->resize(10, 30);

in the hopes that the 10 would be ignored (and expanded) and the 30 would stay fixed, but the widget continues to be sized much smaller.

Thanks!

Marlon

3 Answers3

1

Resizing -- changing widget's geometry -- is not how you use the Fixed size policy. You need to give the fixed size in your own reimplementation of QSize sizeHint() const. Add the following to your widget:

class MyWidget : public QWidget {
...
protected:
    QSize sizeHint() const { return QSize(10, 30); }
...
};

Per Qt's very own documentation:

QSizePolicy::Fixed The QWidget::sizeHint() is the only acceptable alternative, so the widget can never grow or shrink (e.g. the vertical direction of a push button).

Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313
0

So basically you want the Qlabels to be in a QHBoxLayout and not the complete widget? If that's the case then you can simply add only the QLabels to a QHBoxLayout and add it to your menu item widget (don't set the menu item widget with QHBoxLayout)

Chenna V
  • 10,185
  • 11
  • 77
  • 104
  • I actually figured out a way to do it. I set the QHBoxLayout margins to 0: layout->setContentsMargins(5, 0, 0, 0); and then set the label maximum and minimum heights to 30: label->setMaximumHeight(30); label->setMinimumHeight(30); The layout is still resizing my widget to the height of the label, but the label itself is providing the "padding" space that I wanted. It still seems weird that the layout took over the size of its parent widget, but oh well. –  Sep 14 '11 at 18:45
  • the layout should be applied to only children not to the parent. Maybe you have another layout that your parent is contained in – Chenna V Sep 14 '11 at 18:47
  • Yeah it's strange. It is applying to the children, but resizing the parent to be the minimum size to fit the children. Thanks for the help though. –  Sep 14 '11 at 19:05
0

Not tested, but perhaps an idea: layout->setSizeConstraint( QLayout::SetNoConstraint ) perhaps in combination with widget->setFixedHeight(). Good luck!

Robin
  • 1,658
  • 15
  • 26