Qt Layout problem: better explained.

  • I'm writing my own class, very similar to a toolbar, which will contain widgets under a horizontal box layout object inside of it. I have a widget class serving as a container I have a widget class deriving from QPushButton, for custom painting (really showing a loaded image at pos 0,0).

    I initialize a layout object:

    @this->buttonLayout = new QHBoxLayout(this);
    this->buttonLayout->setContentsMargins(0, 0, 0, 0);

    and then i start initializing widgets and "adding" them onto the layout similar to this:

    @// once button is created.. add it...

    In the end, I create a spacer object to make sure all my toolbar buttons are aligned to the left.

    @QSpacerItem * spacerItem = new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Expanding);

    My button class is defining a "setMinimumSize" in the constructor which is correct under a debugger. It's also redefining "hintSize" which is called during runtime and the values are correct.

    My problem is this:

    I load 3 "buttons" onto the toolbar. All have variable sizes. if the Spacing on the layout is 0 the first two buttons will be truncated by 9 pixels exactly!, but the third one will be okay. if the layout spacing is -1 the buttons will show nicely with their variable size, but will have a two pixel space between them (I don't want any space). Lastly, if the layout spacing is "9", Everything will show up fine.

    Why is spacing "0" messing up the button layout causing an overlay? Where did the number "9" come from? why are the first two buttons (e.g. everything but the last button) truncated by exactly 9 pixels when spacing is "0"?

    I couldn't find an answer anywhere.

  • The culprit is the Spacer object. But I don't know why.

    When it's set to "QSizePolicy::Expanding" for its horizontal policy, it simply takes TOO MUCH out of available space, shrinking the other objects.

    If i convert its horizontal policy to "QSizePolicy::Expanding", I can simulate the problem by putting too much.

    Now the question remains: why the heck is the "QSizePolicy::Expanding" allowing itself too much space to begin with?

  • Is that a bug?

  • If I were to do the same thing, I would just have added a stretch @this->buttonLayout->addStretch()@ Maybe that's exactly the same thing, just a different way to do it, I'm not sure, but you might give it a try to see if it causes the same problem.

Log in to reply