Important: Please read the Qt Code of Conduct -

Force horizontal spacer in a grid layout to take exactly half the space (and a button other half)

  • I have 3 groupboxes (highlighted green in the image) all use the grid layout. The first two groupboxes contain two buttons side by side so both buttons take exactly half the horizontal space.

    The third groupbox contains just one button and I would like this button to also take exactly half the horizontal space. When the button is by itself in the groupbox it just stretches to fill the entire space. If I insert a horizontal spacer it instead shrinks to minimum space. I would like the button to take exactly half the space so its size matches with that of the buttons in the other groupboxes.

    0_1536066795562_horizontal spacer.png

  • Lifetime Qt Champion


    Can you show how you setup your QGroupBox ?

    It looks like it doesn't have a layout.

  • Moderators

    @fugreh This is kind of a weird thing to do in a gui, but if you really want to you're going to have to calculate and set the size yourself.

    Just set your button's minimumSize to be the same size as one of the buttons you want to mimic. Then keep your horizontal spacer as is.

    Like I said it's a bit weird though. That's not really how you want to work with layouts imo. If it were me I would have horizontal spacers in all the group boxes to compress the buttons a bit. Extra large white space on buttons always looked really weird to me.

  • @ambershark Well the problem is that this whole panel can be stretched horizontally so the size of the other buttons might change so I can't just set this button's size statically

    @SGaist Hi, here is a screenshot from QtCreator. The groupbox has a grid layout. I tried other layouts, to no avail though.

  • Lifetime Qt Champion

    Code wise using:

    QGroupBox *groupBox = new QGroupBox(tr("My Group Box"));
    QGridLayout *layout = new QGridLayout(groupBox);
    layout->addWidget(new QPushButton(tr("My Nice Button")), 0, 0);
    layout->setColumnStretch(0, 1);
    layout->setColumnStretch(1, 1);

    does what you want.