0

I have created a pyqt5 window which has a vertical layout. Inside this vertical layout, I have added 2 buttons. By default these are vertically aligned like below:

enter image description here

How can I adjust the geometry of the buttons to move above. Expected output like below:

enter image description here

so that if I add 3rd button, it goes below button 2. Below is the code:

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QPushButton


class MainWindow(QMainWindow):

    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)

        layout = QVBoxLayout()
        widget = QWidget()
        widget.setLayout(layout)
        self.setCentralWidget(widget)

        button1 = QPushButton('Button 1', self)
        layout.addWidget(button1)

        button2 = QPushButton('Button 2', self)
        layout.addWidget(button2)


app = QApplication(sys.argv)
main_window = MainWindow()
main_window.show()
sys.exit(app.exec_())
S Andrew
  • 5,592
  • 27
  • 115
  • 237

1 Answers1

1

You need to set the alignment of your layout and add some spacing between the widgets you added, like this:

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QPushButton
from PyQt5 import QtCore


class MainWindow(QMainWindow):

    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)

        layout = QVBoxLayout()
        #set spacing between your widgets
        layout.setSpacing(5)
        #set alignment in your vertical layout
        layout.setAlignment(QtCore.Qt.AlignTop)
        widget = QWidget()
        widget.setLayout(layout)

        self.setCentralWidget(widget)

        button1 = QPushButton('Button 1', self)
        layout.addWidget(button1)

        button2 = QPushButton('Button 2', self)
        layout.addWidget(button2)


app = QApplication(sys.argv)
main_window = MainWindow()
main_window.show()
sys.exit(app.exec_())
jairoar
  • 217
  • 1
  • 9
  • Thanks. I am actually designing the UI from qt desginer. Is it possible to set alignment of layout in qt designer. – S Andrew Sep 15 '20 at 16:13
  • 1
    I think yes, check this: [Designer Alignment](https://stackoverflow.com/questions/42741396/qvboxlayout-how-to-align-widgets-to-the-top-using-qt-designer) aditionally you can set the size of your VBox as fixed and the widgets inside wont move. – jairoar Sep 15 '20 at 16:19