search
HomeBackend DevelopmentPython TutorialLayout management that you must learn every day in PyQt5

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

Layout management that you must learn every day in PyQt5

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

Layout management that you must learn every day in PyQt5

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

Layout management that you must learn every day in PyQt5

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

Layout management that you must learn every day in PyQt5

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Merging Lists in Python: Choosing the Right MethodMerging Lists in Python: Choosing the Right MethodMay 14, 2025 am 12:11 AM

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

How to concatenate two lists in python 3?How to concatenate two lists in python 3?May 14, 2025 am 12:09 AM

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Python concatenate list stringsPython concatenate list stringsMay 14, 2025 am 12:08 AM

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

Python execution, what is that?Python execution, what is that?May 14, 2025 am 12:06 AM

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Python: what are the key featuresPython: what are the key featuresMay 14, 2025 am 12:02 AM

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.