欢迎访问宙启技术站
智能推送

PySide2.QtWidgets中的布局管理器

发布时间:2023-12-25 17:46:44

在PySide2.QtWidgets中,布局管理器用于将小部件放置在窗口或其他父控件中的特定位置。使用布局管理器可以确保小部件在窗口大小发生变化时能够自动调整其位置和大小。在PySide2.QtWidgets中,有四种常用的布局管理器:QHBoxLayout、QVBoxLayout、QGridLayout和QFormLayout。下面是每种布局管理器的使用示例。

1. QHBoxLayout(水平布局管理器):

import sys
from PySide2.QtWidgets import QApplication, QWidget, QPushButton, QHBoxLayout

app = QApplication(sys.argv)

# 创建一个应用程序窗口
window = QWidget()

# 创建一个水平布局管理器
layout = QHBoxLayout()

# 创建两个按钮
button1 = QPushButton("Button 1")
button2 = QPushButton("Button 2")

# 将按钮添加到布局管理器中
layout.addWidget(button1)
layout.addWidget(button2)

# 将布局管理器设置为窗口的主布局管理器
window.setLayout(layout)

# 显示窗口
window.show()

# 运行应用程序
sys.exit(app.exec_())

在这个例子中,我们创建了一个应用程序窗口,并在窗口中添加了两个按钮。然后,我们创建了一个水平布局管理器,并将两个按钮添加到布局管理器中。最后,我们将布局管理器设置为窗口的主布局管理器,并显示窗口。

2. QVBoxLayout(垂直布局管理器):

import sys
from PySide2.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout

app = QApplication(sys.argv)

# 创建一个应用程序窗口
window = QWidget()

# 创建一个垂直布局管理器
layout = QVBoxLayout()

# 创建两个按钮
button1 = QPushButton("Button 1")
button2 = QPushButton("Button 2")

# 将按钮添加到布局管理器中
layout.addWidget(button1)
layout.addWidget(button2)

# 将布局管理器设置为窗口的主布局管理器
window.setLayout(layout)

# 显示窗口
window.show()

# 运行应用程序
sys.exit(app.exec_())

与水平布局管理器类似,垂直布局管理器将小部件按照垂直方向排列。

3. QGridLayout(网格布局管理器):

import sys
from PySide2.QtWidgets import QApplication, QWidget, QPushButton, QGridLayout

app = QApplication(sys.argv)

# 创建一个应用程序窗口
window = QWidget()

# 创建一个网格布局管理器
layout = QGridLayout()

# 创建四个按钮,分别按行列添加到网格布局管理器中
buttons = []
for i in range(4):
    button = QPushButton("Button {}".format(i+1))
    buttons.append(button)
    row = i // 2
    col = i % 2
    layout.addWidget(button, row, col)

# 将布局管理器设置为窗口的主布局管理器
window.setLayout(layout)

# 显示窗口
window.show()

# 运行应用程序
sys.exit(app.exec_())

在网格布局管理器中,我们可以将小部件按照行和列的方式组织起来。在这个例子中,我们创建了一个网格布局管理器,然后创建四个按钮并按照2x2的网格添加到布局管理器中。

4. QFormLayout(表单布局管理器):

import sys
from PySide2.QtWidgets import QApplication, QWidget, QLabel, QLineEdit, QFormLayout

app = QApplication(sys.argv)

# 创建一个应用程序窗口
window = QWidget()

# 创建一个表单布局管理器
layout = QFormLayout()

# 创建两个标签和两个文本框
label1 = QLabel("Name:")
lineEdit1 = QLineEdit()
label2 = QLabel("Age:")
lineEdit2 = QLineEdit()

# 将标签和文本框按照键值对的方式添加到布局管理器中
layout.addRow(label1, lineEdit1)
layout.addRow(label2, lineEdit2)

# 将布局管理器设置为窗口的主布局管理器
window.setLayout(layout)

# 显示窗口
window.show()

# 运行应用程序
sys.exit(app.exec_())

表单布局管理器可用于创建带有标签和文本框的表单,其中标签和文本框按照键值对的方式排列。在这个例子中,我们创建了一个表单布局管理器,并创建了两个标签和两个文本框,然后将它们添加到布局管理器中。

这些是PySide2.QtWidgets中常用的布局管理器的示例。通过使用这些布局管理器,我们可以方便地组织和调整小部件的位置和大小。