PyQt5 提供了多种布局管理器来帮助你组织界面元素,使它们能够自动调整大小和排列以适应窗口的变化。下面是 PyQt5 中主要布局管理器的介绍及简单示例:
1. QHBoxLayout(水平布局)
水平布局将子控件从左到右排列。
示例:
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QHBoxLayout
app = QApplication([])
window = QWidget()
layout = QHBoxLayout()
button1 = QPushButton("按钮1")
button2 = QPushButton("按钮2")
button3 = QPushButton("按钮3")
layout.addWidget(button1)
layout.addWidget(button2)
layout.addWidget(button3)
window.setLayout(layout)
window.setWindowTitle("QHBoxLayout 示例")
window.show()
app.exec_()
2. QVBoxLayout(垂直布局)
垂直布局将子控件从上到下排列。
示例:
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout
app = QApplication([])
window = QWidget()
layout = QVBoxLayout()
button1 = QPushButton("按钮1")
button2 = QPushButton("按钮2")
button3 = QPushButton("按钮3")
layout.addWidget(button1)
layout.addWidget(button2)
layout.addWidget(button3)
window.setLayout(layout)
window.setWindowTitle("QVBoxLayout 示例")
window.show()
app.exec_()
3. QGridLayout(网格布局)
网格布局允许你在一个二维网格中排列控件。
示例:
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QGridLayout
app = QApplication([])
window = QWidget()
layout = QGridLayout()
button1 = QPushButton("1")
button2 = QPushButton("2")
button3 = QPushButton("3")
button4 = QPushButton("4")
layout.addWidget(button1, 0, 0)
layout.addWidget(button2, 0, 1)
layout.addWidget(button3, 1, 0)
layout.addWidget(button4, 1, 1)
window.setLayout(layout)
window.setWindowTitle("QGridLayout 示例")
window.show()
app.exec_()
4. QFormLayout(表单布局)
表单布局用于排列标签和字段(如输入框)成一对的形式。
示例:
from PyQt5.QtWidgets import QApplication, QWidget, QLineEdit, QLabel, QFormLayout
app = QApplication([])
window = QWidget()
layout = QFormLayout()
lineEdit1 = QLineEdit()
lineEdit2 = QLineEdit()
layout.addRow(QLabel("名字:"), lineEdit1)
layout.addRow(QLabel("年龄:"), lineEdit2)
window.setLayout(layout)
window.setWindowTitle("QFormLayout 示例")
window.show()
app.exec_()
5. QStackedLayout(堆叠布局)
堆叠布局允许你将多个控件堆叠起来,每次只显示一个。
示例:
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QStackedLayout, QPushButton
app = QApplication([])
window = QWidget()
layout = QStackedLayout()
page1 = QLabel("第一页")
page2 = QLabel("第二页")
layout.addWidget(page1)
layout.addWidget(page2)
button1 = QPushButton("显示第一页")
button1.clicked.connect(lambda: layout.setCurrentIndex(0))
button2 = QPushButton("显示第二页")
button2.clicked.connect(lambda: layout.setCurrentIndex(1))
mainLayout = QVBoxLayout()
mainLayout.addLayout(layout)
mainLayout.addWidget(button1)
mainLayout.addWidget(button2)
window.setLayout(mainLayout)
window.setWindowTitle("QStackedLayout 示例")
window.show()
app.exec_()
6. Absolute Layout(绝对布局)
虽然PyQt5没有直接的绝对布局类,但你可以通过手动设置控件的位置(move()
)来实现类似效果,但这种做法不推荐,因为它不灵活,难以适配不同分辨率和窗口大小变化。
7. Flow Layout(流式布局)
流式布局没有直接内置在PyQt5中,但可以自己实现,用于动态地根据空间填充控件,如同HTML中的<div>
元素的display: flow;
。
示例(简化版,非内置):
# 流式布局的简单实现不在标准库中,此处不提供完整示例代码,但你可以参考第三方库或自定义类来实现。
以上布局管理器在实际开发中可根据需要组合使用,以构建复杂且响应式良好的用户界面。
当前文章价值8.15元,扫一扫支付后添加微信提供帮助!(如不能解决您的问题,可以申请退款)
评论已关闭!