简体   繁体   中英

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:

在此处输入图片说明

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

在此处输入图片说明

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM