Search code examples
pythonbuttonpyqt5vertical-alignment

How to adjust the geometry of widgets added in vertical box layout in pyqt5


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_())

Solution

  • 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_())