Layout spacing
-
When I run the code below I get these buttons, with big vertical spaces on Mac:
#include <QVBoxLayout> #include <QPushButton> class Buttons : public QWidget { public: Buttons( QWidget* parent ); }; Buttons::Buttons( QWidget* parent ) :QWidget( parent ) { setContentsMargins( 0, 0, 0, 0 ); QHBoxLayout* hLayout = new QHBoxLayout( this ); hLayout->setSpacing( 0 ); hLayout->setContentsMargins( 0, 0, 0, 0 ); hLayout->setMargin( 0 ); QPushButton* button1 = new QPushButton( QString( "Button 1" ), this ); button1->setAttribute( Qt::WA_MacSmallSize ); hLayout->addWidget( button1 ); QPushButton* button2 = new QPushButton( QString( "Button 2" ), this ); button2->setAttribute( Qt::WA_MacSmallSize ); hLayout->addWidget( button2 ); } class MainWindow : public QWidget { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); }; MainWindow::MainWindow(QWidget *parent) : QWidget(parent) { setContentsMargins( 0, 0, 0, 0 ); QVBoxLayout* v1Layout = new QVBoxLayout( this ); v1Layout->setContentsMargins( 0, 0, 0, 0 ); v1Layout->setMargin( 0 ); v1Layout->setSpacing( 0 ); for ( int i = 0; i < 10; i++ ) { Buttons* buttons = new Buttons( this ); v1Layout->addWidget( buttons ); } }
I can't work out how to get rid of the vertical spacing between buttons. Note that I don't seem to have the same problem on Windows.
If I replace the Buttons class with a simple QButton, then the extra spacing disappears.
So it seems to be something to do with the QHBoxLayout. Any ideas?
I am using Qt 5.15.2.
-
I can push the buttons closer together by setting in the Buttons constructor for Mac:
setContentsMargins( 0, 0, 0, -4 );
That seems like a very ugly solution though!
@AndyBrice Your code may behave differently on other OS. What will happen if you resize your app? Even -4 may need to be scaled if it is set in full screen mode.
Play with the factor in the spacer to see if there is any help. Sometimes I have to raise the factor to get what I want.
Another idea would be to make your layout inside Qt Designer to see if it works there. If it works, generate the layout code. Copy it into your code.