c++qtqsplitter

How to prevent QSplitter child from collapsing before completely minimizing its size to 0


I'm trying to get a horizontal QSplitter to allow me to resize one of its children's width to 0 without it collapsing before reaching the edge.

Here's an example of QSplitter with 2 children, a QWidget, and a QPushButton, where the button collapses before I drag it to the edge:

Unwanted collapsing behavior

Minimal Reproducible example:

QSplitter *splitter = new QSplitter();
QWidget *widget = new QWidget;
QPushButton *button = new QPushButton("button");

widget->setStyleSheet("background: darkblue;");

splitter->addWidget(button);
splitter->addWidget(widget);

splitter->show();

splitter->setMinimumSize(100,100);

I tried:

All made no difference.

The closest question to my case that I found here is this one: How do I prevent QSplitter from hiding child widgets completely?, which did not help.

Using an event filter, I noticed a QInputMethodQueryEvent triggered when the button collapses, but I do not know how to use that.

I also noticed that the behavior I'm looking to achieve is possible with QWidget, QFrame, here's how it looks with 2 QWidgets in a QSplitter:

Normal collapsing behavior

Based on this observation, I managed to find a workaround, by placing the widget I need (button for example) inside a QWidget, and making the container widget a child of QSplitter, and it works, but I'd rather avoid using this method.

What is causing this behavior? And how do I change it so that the button resizes until its width reaches 0 without collapsing?


Solution

  • The reason why the button is not resized is because QSplitter respects size policy of the button. Setting it to QSizePolicy::Ignored allows QSplitter to freely resize the button.

    auto * button = new QPushButton();
    button->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Fixed);