pythonqtpyqt5qpushbuttonqvboxlayout

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?


Solution

  • 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