Python hosting : Host, run, and code Python in the cloud!
A window can contain widgets (buttons, text field, image and others). Widgets are frequently added to a layout. A horizontal layout can be used to (dynamically) add widgets in horizontal direction.
In this article we’ll show you how to add buttons in the horizontal direction using a horizontal layout.
Related course:
Horizontal layout example We will show the whole code and then explain.
import sysfrom PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QHBoxLayout, QGroupBox, QDialog, QVBoxLayoutfrom PyQt5.QtGui import QIconfrom PyQt5.QtCore import pyqtSlotclass App (QDialog ): def __init__ (self ): super ().__init__() self.title = 'PyQt5 layout - pythonspot.com' self.left = 10 self.top = 10 self.width = 320 self.height = 100 self.initUI() def initUI (self ): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) self.createHorizontalLayout() windowLayout = QVBoxLayout() windowLayout.addWidget(self.horizontalGroupBox) self.setLayout(windowLayout) self.show() def createHorizontalLayout (self ): self.horizontalGroupBox = QGroupBox("What is your favorite color?" ) layout = QHBoxLayout() buttonBlue = QPushButton('Blue' , self) buttonBlue.clicked.connect(self.on_click) layout.addWidget(buttonBlue) buttonRed = QPushButton('Red' , self) buttonRed.clicked.connect(self.on_click) layout.addWidget(buttonRed) buttonGreen = QPushButton('Green' , self) buttonGreen.clicked.connect(self.on_click) layout.addWidget(buttonGreen) self.horizontalGroupBox.setLayout(layout) @pyqtSlot() def on_click (self ): print ('PyQt5 button click' ) if __name__ == '__main__' : app = QApplication(sys.argv) ex = App() sys.exit(app.exec_())
Explanation
We start by calling the method self.createHorizontalLayout() inside the initUI() method. Inside the method we create a box with a title and a horizontal layout:
self.horizontalGroupBox = QGroupBox("What is your favorite color?" ) layout = QHBoxLayout()
We create widgets (in this example qpushbutton ) and add them to the layout one by one:
buttonBlue = QPushButton('Blue' , self) buttonBlue.clicked.connect(self.on_click) layout.addWidget(buttonBlue)
We set the title-box to contain the horizontal layout:
self.horizontalGroupBox.setLayout(layout)
In the initUI method we add it to the window:
windowLayout = QVBoxLayout() windowLayout.addWidget(self.horizontalGroupBox) self.setLayout(windowLayout)
You can also create a vertical layout with a qvboxlayout .
If you are new to programming Python PyQt, I highly recommend this book.
Download PyQT5 Examples
Leave a Reply: