PyQt5:QVBoxLayout:如何将三个按钮组合在一起?

PyQt5: QVBoxLayout: how to make three buttons as a group?

所以我用 QVBoxLayout 制作了一个简单的 PyQt5 应用程序。显然,我添加的每个按钮都从一端延伸到另一端,并且它们都堆叠在一起。我如何向 QVBoxLayout 添加按钮,这些按钮将是我屏幕上的一组三个小按钮?

所以你的按钮需要一个 QHBoxLayout,嵌套在 QVBoxLayout:

class Main(QMainWindow):
    def __init__(self, parent=None):
        super(Main, self).__init__(parent)
        self.centralWidget = QWidget()
        self.setCentralWidget(self.centralWidget)

        self.vLayout = QVBoxLayout(self.centralWidget)

        self.buttonsWidget = QWidget()
        self.buttonsWidgetLayout = QHBoxLayout(self.buttonsWidget)
        self.buttons = [QPushButton(c) for c in 'ABC']
        for button in self.buttons:
            self.buttonsWidgetLayout.addWidget(button)

        self.placeHolder = QWidget()
        self.placeHolder.setMinimumWidth(480)
        self.placeHolder.setMinimumHeight(320)
        self.placeHolder.setStyleSheet('* {background: red;}')

        self.vLayout.addWidget(self.placeHolder)
        self.vLayout.addWidget(self.buttonsWidget)

为了确保元素不被拉伸,你可以使用一个特殊的 QSpacerItem 元素。

试一试:

from PyQt5 import Qt


class Widget(Qt.QWidget):

    def __init__(self):
        super().__init__()
        layout = Qt.QVBoxLayout(self)

        btn_layout = Qt.QHBoxLayout()
        # !!!
        btn_layout.addItem(Qt.QSpacerItem(0, 0, Qt.QSizePolicy.Expanding, Qt.QSizePolicy.Minimum))

        btn1 = Qt.QPushButton("Button 1")
        btn2 = Qt.QPushButton("Button 2")
        btn3 = Qt.QPushButton("Button 3")

        btn_layout.addWidget(btn1)
        btn_layout.addWidget(btn2)
        btn_layout.addWidget(btn3)

        table = Qt.QTableWidget()
        table.setRowCount(5)
        table.setColumnCount(5)
        layout.addWidget(table)
        layout.addLayout(btn_layout)


if __name__ == '__main__':
    app = Qt.QApplication([])
    w = Widget()
    w.show()
    app.exec()