A.Bg
A.Bg

Reputation: 65

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

So I have made a simple PyQt5 application with a QVBoxLayout. Obviously, each button I add stretches out from one end to another and they all stack on on top of each other. How can I add buttons to QVBoxLayout that would be a group of three small buttons on my screen?

Upvotes: 1

Views: 3729

Answers (2)

fferri
fferri

Reputation: 18950

So you need a QHBoxLayout for your buttons, nested in a 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)

Screenshot

Upvotes: 3

S. Nick
S. Nick

Reputation: 13661

To ensure that the elements are not stretched, you can use a special QSpacerItem element.

Try it:

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

enter image description here

Upvotes: -1

Related Questions