3
votes

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

3 Answers

1
votes

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

0
votes

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)

0
votes

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