This article mainly introduces in detail the relevant information about layout management that must be learned every day in PyQt5. It has a certain reference value. Interested friends can refer to it.
There is a guide in GUI programming The part that cannot be ignored is layout management. Layout management controls how our controls are placed in the application window. Layout management can be done in two ways. We can use absolute positioning or layout class methods to control the position of controls in the program window.
Absolute positioning
Each control is placed at the position specified by the programmer. When you use absolute positioning, we need to be aware of the following limitations:
If we resize the window the size and position of the control remain the same
The application may look different on different platforms
Changing fonts may break the layout of the application
If you decide to change the layout, we Each control must be completely modified, which is tedious and time-consuming
The following example is the absolute coordinate positioning method of the control.
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ PyQt5 教程 这个例子显示了在窗口中使用绝对定位的三个标签。 作者:我的世界你曾经来过 博客:http://blog.csdn.net/weiaitaowang 最后编辑:2016年7月31日 """ import sys from PyQt5.QtWidgets import QApplication, QWidget, QLabel class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): lbl1 = QLabel('我的世界你曾经来过', self) lbl1.move(15, 10) lbl2 = QLabel('CSND博客', self) lbl2.move(35, 40) lbl3 = QLabel('程序员', self) lbl3.move(55, 70) self.setGeometry(300, 300, 250, 150) self.setWindowTitle('绝对定位') self.show() if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_())
In our examples, labels are used. We position them by providing x and y coordinate values. The origin of the coordinate system is the upper left corner of the control. The x value increases from left to right. The y value increases from top to bottom.
lbl1 = QLabel('我的世界你曾经来过', self) lbl1.move(15, 10)
The label control is placed at x=15 and y=10.
After program execution
Box layout box layout
How to use layout class for layout management More flexible and practical. It is the preferred way to place a control in a window. QHBoxLayout and QVBoxLayout are the basic layout classes for horizontally and vertically aligned controls respectively.
Just imagine, we want to put two buttons in the lower right corner of the program. To create such a layout, we can use two boxes, one horizontal and one vertical. To create the necessary free space, we will add a stretch factor.
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ PyQt5 教程 在这个例子中,我们在窗口的右下角放置两个按钮。 作者:我的世界你曾经来过 博客:http://blog.csdn.net/weiaitaowang 最后编辑:2016年7月31日 """ import sys from PyQt5.QtWidgets import (QApplication, QWidget, QPushButton, QVBoxLayout, QHBoxLayout) class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): okButton = QPushButton('确定') cancelButton = QPushButton('取消') 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, 350, 150) self.setWindowTitle('Box布局') self.show() if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_())
This example places two buttons in the lower right corner of the window. When we resize application windows, they are fixed to the lower right corner. We use both HBoxLayout and QVBoxLayout layouts.
okButton = QPushButton('确定') cancelButton = QPushButton('取消')
Here we have created two buttons.
hbox = QHBoxLayout() hbox.addStretch(1) hbox.addWidget(okButton) hbox.addWidget(cancelButton)
We created a horizontal box layout, increased the stretch factor (addStretch), and added (addWidget) two buttons. Added a stretch factor before adding the two buttons, which will push the two buttons to the right side of the window.
vbox = QVBoxLayout() vbox.addStretch(1) vbox.addLayout(hbox)
To get the layout we want, we also need to put the horizontal layout into a vertical layout. A stretch factor on the vertical box will push the horizontal box, including the controls inside it, to the bottom of the window.
self.setLayout(vbox)
Finally, we set the main layout of the window.
After program execution
QGridLayout Grid layout
The most commonly used layout class is grid layout . This layout divides the space into rows and columns. To create a grid layout, we use the QGridLayout class.
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ PyQt5 教程 在这个例子中,我们使用网格布局创建一个计算器的框架。 作者:我的世界你曾经来过 博客:http://blog.csdn.net/weiaitaowang 最后编辑:2016年7月31日 """ import sys from PyQt5.QtWidgets import (QApplication, QWidget, QPushButton, QGridLayout) 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('计算器') self.show() if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_())
In our example, we will place the created button control in a grid.
grid = QGridLayout() self.setLayout(grid)
Instantiate QGridLayout and set the layout of the application window.
names = ['Cls', 'Bck', '', 'Close', '7', '8', '9', '/', '4', '5', '6', '*', '1', '2', '3', '-', '0', '.', '=', '+',]
This is the button label that will be used in the future.
positions = [(i, j) for i in range(5) for j in range(4)]
xWe create a list of grid locations.
for position, name in zip(positions, names): if name == '': continue button = QPushButton(name) grid.addWidget(button, *position)
Create a button and add (addWidget) to the layout.
After the program is executed
Expand the grid layout
The controls in the window can span across the grid Multiple columns or rows. In the following example we illustrate this.
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ PyQt5 教程 在这个例子中,我们使用GridLayout的跨行创建了一个更复杂的窗口布局。 作者:我的世界你曾经来过 博客:http://blog.csdn.net/weiaitaowang 最后编辑:2016年7月31日 """ import sys from PyQt5.QtWidgets import (QApplication, QWidget, QLabel, QTextEdit, QLineEdit, QGridLayout) class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): title = QLabel('标题') author = QLabel('作者') review = QLabel('评论') 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('评论') self.show() if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_())
The program we created contains three labels, two single-line text input boxes and a text editing control. Use QGridLayout layout.
grid =QGridLayout() grid.setSpacing(10)
Instance the grid layout and set the spacing.
grid.addWidget(reviewEdit, 3, 1, 5, 1)
Add a control to the grid layout, we can use row span or column span for this control. In our example, we require the reviewEdit control to span 5 rows.
After program execution
This part of the PyQt5 tutorial is dedicated to layout management. The event-related content of PyQt5 will be introduced later.
related suggestion:
PyQt5 Must Learn Every Day Check Boxes with Labels
PyQt5 Must Learn Every Day Create Window Centering Effect
PyQt5 Must learn to close the window every day
The above is the detailed content of Layout management that you must learn every day in PyQt5. For more information, please follow other related articles on the PHP Chinese website!

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool