温馨提示:本文翻译自stackoverflow.com,查看原文请点击:python - How to adjust the geometry of widgets added in vertical box layout in pyqt5
button pyqt5 python vertical-alignment

python - 如何调整在pyqt5的垂直框布局中添加的小部件的几何形状

发布于 2021-03-31 00:01:12

我创建了一个pyqt5具有vertical布局窗口在此垂直布局内,我添加了2个按钮。默认情况下,它们是垂直对齐的,如下所示:

在此处输入图片说明

我如何调整按钮的几何形状以移至上方。预期输出如下:

在此处输入图片说明

这样,如果我添加第三个按钮,它将位于按钮2下方。下面是代码:

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
被浏览
0
jairoar 2020-09-15 23:45

你需要设置布局的对齐方式,并在所添加的小部件之间添加一些间距,如下所示:

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