Strange behavior of margins for Qt controls

649 Views Asked by At

I have just started using Qt (5.3) and encountered the fact that some controls appears with margins which I cannot control.

First, I tried to put QLabel and QPushButton right inside QMainWindow

window = new QMainWindow;
label = new QLabel( title, window );

In this case label appears with a margin of 12 pixels at the top (see picture). QPushButton appears with 1 pixel top & left margins. But if I insert QFrame with a border, it appears without any margin.

https://i.stack.imgur.com/Dsll7.jpg

So the margins seem to be attributes of QLabel and QPushButton. BUT:

When I tried to add extra QFrame between windows and controls:

window = new QMainWindow;
frame = new QFrame(window );
label = new QLabel( title, frame);

I had got different picture: QLabels top margin had shortened to 1 pixel QPushButton 1 pixel margins remained intact, but the height of the button had changed

I have tried: setStyleSheet( "padding:0px" ) and setContentsMargins( 0, 0, 0, 0 )

for all elements, but without any success.

Any help would be greatly appreciated

1

There are 1 best solutions below

2
On

The QMainWindow class isn't designed to have widgets added to it directly. Whatever results you see are due to this fact.

The "margins" that you see are not really margins. Since a QLabel is a QFrame, you can enable its frame to see that it has no margin - merely the text is offset from the edge, and that's by design. You can similarly overlay a same-size translucent rectangle on a QPushButton to see that there is also no margin, merely the styling adds its own platform-specific margin. Do not mistake the platform styling mechanism for the style sheets: they are two separate mechanisms and mostly exclusive, with the use of the latter disabling the effects of the former, with few exceptions. For example, the stylesheet spacing/margins/padding is additive to whatever the platform style mandates.

See this answer for an example of how to show overlays on any widget without subclassing.