Layout management in pyqt5
Layout management is an important aspect of GUI programming. Layout management is a way to prevent components in the application window. We can manage the layout in two basic ways. We can use absolute positioning and layout classes.
Absolute Positioning
The Program specifies the position of the component and the size of each component is measured in pixels. When you use absolute positioning, we need to know the following restrictions:
- If we change the window size, the position and size of the component will not change.
- Applications may have different appearances on different platforms.
- Changing the font in our application may make the application a mess.
- If we decide to change our layout, we must completely rewrite our layout, which is boring and time-consuming.
In the following example, absolute coordinates are used to locate the component.
#!/usr/bin/python3# -*- coding: utf-8 -*-"""ZetCode PyQt5 tutorial This example shows three labels on a windowusing absolute positioning. author: Jan Bodnarwebsite: zetcode.com last edited: January 2015"""import sysfrom PyQt5.QtWidgets import QWidget, QLabel, QApplicationclass Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): lbl1 = QLabel(‘Zetcode‘, self) lbl1.move(15, 10) lbl2 = QLabel(‘tutorials‘, self) lbl2.move(35, 40) lbl3 = QLabel(‘for programmers‘, self) lbl3.move(55, 70) self.setGeometry(300, 300, 250, 150) self.setWindowTitle(‘Absolute‘) self.show() if __name__ == ‘__main__‘: app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_())
We use the move () method to locate our components. In the above example, we used the move () method to locate some label components. When we use the move () method, we provide the X and Y coordinates for the move () method as parameters. The coordinate system used by move () is calculated from the upper left corner. The X value increases from left to right. The Y value increases from top to bottom.
lbl1 = QLabel(‘Zetcode‘, self)lbl1.move(15, 10)
Position the tag component in the coordinates of X = 15, y = 10.
Figure: absolute positioning
Box Layout
The layout management class of the layout manager is flexible and practical. It is the preferred method for locating components in a window. Qhboxlayout and qvboxlayout are two basic layout management classes, which are horizontally or vertically arranged linear components. Imagine we need to arrange two buttons in the lower right corner. To use the box layout, we will use a horizontal box layout and a vertical box layout. To use some necessary blank spaces, we will also add some tensile factors.
#!/usr/bin/python3# -*- coding: utf-8 -*-"""ZetCode PyQt5 tutorial In this example, we position two pushbuttons in the bottom-right corner of the window. author: Jan Bodnarwebsite: zetcode.com last edited: January 2015"""import sysfrom PyQt5.QtWidgets import (QWidget, QPushButton, QHBoxLayout, QVBoxLayout, QApplication)class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): okButton = QPushButton("OK") cancelButton = QPushButton("Cancel") hbox = QHBoxLayout() hbox.addStretch(1) hbox.addWidget(okButton) hbox.addWidget(cancelButton) vbox = QVBoxLayout() vbox.addStretch(1) vbox.addLayout(hbox) self.setLayout(vbox) self.setGeometry(300, 300, 300, 150) self.setWindowTitle(‘Buttons‘) self.show() if __name__ == ‘__main__‘: app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_())
In the example, two buttons are placed in the lower right corner. When we change the size of the application window, they do not change their positions relative to the application window. In this example, we use the qhboxlayout and qvboxlayout layout classes.
okButton = QPushButton("OK")cancelButton = QPushButton("Cancel")
Here we have created two buttons.
hbox = QHBoxLayout()hbox.addStretch(1)hbox.addWidget(okButton)hbox.addWidget(cancelButton)
Here we create a horizontal box layout and add a stretch factor and two buttons. The stretch factor adds a scalable space before the two buttons. This pushes the button to the right of the window.
vbox = QVBoxLayout()vbox.addStretch(1)vbox.addLayout(hbox)
To create the necessary layout, we place the horizontal layout in the vertical layout. The stretch factor pushes the horizontal box layout containing two buttons to the bottom side of the window.
self.setLayout(vbox)
Finally, let's set the main layout of the window.
Figure: buttons
Grid layout
The most common layout class is grid layout. This layout uses columns to split space. To create a grid layout, we need to use the qgridlayout class.
#!/usr/bin/python3# -*- coding: utf-8 -*-"""ZetCode PyQt5 tutorial In this example, we create a skeletonof a calculator using a QGridLayout.author: Jan Bodnarwebsite: zetcode.com last edited: January 2015"""import sysfrom PyQt5.QtWidgets import (QWidget, QGridLayout, QPushButton, QApplication)class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): grid = QGridLayout() self.setLayout(grid) names = [‘Cls‘, ‘Bck‘, ‘‘, ‘Close‘, ‘7‘, ‘8‘, ‘9‘, ‘/‘, ‘4‘, ‘5‘, ‘6‘, ‘*‘, ‘1‘, ‘2‘, ‘3‘, ‘-‘, ‘0‘, ‘.‘, ‘=‘, ‘+‘] positions = [(i,j) for i in range(5) for j in range(4)] for position, name in zip(positions, names): if name == ‘‘: continue button = QPushButton(name) grid.addWidget(button, *position) self.move(300, 150) self.setWindowTitle(‘Calculator‘) self.show() if __name__ == ‘__main__‘: app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_())
In our example, we created a grid layout that is full of buttons.
grid = QGridLayout()self.setLayout(grid)
Instantiate the qgridlayout class and set this class as the layout of the application window.
names = [‘Cls‘, ‘Bck‘, ‘‘, ‘Close‘, ‘7‘, ‘8‘, ‘9‘, ‘/‘, ‘4‘, ‘5‘, ‘6‘, ‘*‘, ‘1‘, ‘2‘, ‘3‘, ‘-‘, ‘0‘, ‘.‘, ‘=‘, ‘+‘]
These labels will be used in subsequent buttons.
positions = [(i,j) for i in range(5) for j in range(4)]
We have created a grid positioning list.
for position, name in zip(positions, names): if name == ‘‘: continue button = QPushButton(name) grid.addWidget(button, *position)
Create a button component and use the addwidget () method to add a button to the layout.
Figure: calculator skeleton
Text review window example
In a grid, a component can span multiple columns or rows. In this example, we will describe it.
#!/usr/bin/python3# -*- coding: utf-8 -*-"""ZetCode PyQt5 tutorial In this example, we create a bitmore complicated window layout usingthe QGridLayout manager. author: Jan Bodnarwebsite: zetcode.com last edited: January 2015"""import sysfrom PyQt5.QtWidgets import (QWidget, QLabel, QLineEdit, QTextEdit, QGridLayout, QApplication)class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): title = QLabel(‘Title‘) author = QLabel(‘Author‘) review = QLabel(‘Review‘) titleEdit = QLineEdit() authorEdit = QLineEdit() reviewEdit = QTextEdit() grid = QGridLayout() grid.setSpacing(10) grid.addWidget(title, 1, 0) grid.addWidget(titleEdit, 1, 1) grid.addWidget(author, 2, 0) grid.addWidget(authorEdit, 2, 1) grid.addWidget(review, 3, 0) grid.addWidget(reviewEdit, 3, 1, 5, 1) self.setLayout(grid) self.setGeometry(300, 300, 350, 300) self.setWindowTitle(‘Review‘) self.show() if __name__ == ‘__main__‘: app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_())
We created a window that contains three tags, two single-line edit boxes, and a text edit box component. The layout uses the qgridlayout layout.
grid = QGridLayout()grid.setSpacing(10)
We created a grid layout and set the spacing between components.
grid.addWidget(reviewEdit, 3, 1, 5, 1)
If we add a component to the grid layout, we can provide cross-row and cross-Column Parameters of the component. In this example, the reviewedit component is divided into five lines.
Figure: Review example
This section of the pyqt5 tutorial is used to describe layout management.
Pyqt5 tutorial-layout management (4)