Search code examples
c++qtlayoutqt5qlayout

Qt - How to set minimum size on a container so it doesn't distort children


I have a QWidget container (actually a QFrame) with a few widgets inside. The contents of this container (the number and/or size of the child widgets) may change dynamically. The container itself is in a scrollarea.

Generally, the container is properly resized (grown or shrunk) according to its contents. This works.

However, I also need to set a minimum size on this container so it doesn't shrink too much. That is, the container's minimum size should be: max(my_minimum_size, contents_size). This is where it becomes problematic.

If I use container->setMinimumSize(200, 200); and the size of the contents is greater than (200, 200), the container can still be resized to (200, 200) (unlike before), with its contents size ignored and being distorted or chopped off.

Is there a way to fix this? I'm using Qt 5.9.

Update: This Qt Designer UI file shows exactly what I mean. There is a minimumSize set on a container, and resizing it distorts the buttons.


Solution

  • I got my answer at Qt Centre:

    https://www.qtcentre.org/threads/70015-Set-minimum-size-of-a-container-without-distorting-its-children

    1. Create a subclass of QFrame
    2. Override minimumSizeHint() such that it takes the value from the base class and expands it.

    Something like:

    QSize MyFrame::minimumSizeHint() const override
    {
        const QSize baseSize = QFrame::minimumSizeHint();
        return baseSize.expandedTo(QSize(200, 200));
    }