使用PySide.QtGuiQVBoxLayout()创建带有间距的布局
发布时间:2023-12-31 10:54:35
使用 PySide.QtGui.QVBoxLayout() 方法可以创建一个垂直布局,并且可以设置布局内部的控件之间的间距。下面是一个简单的示例代码,展示了如何使用 QVBoxLayout() 创建带有间距的布局:
import sys
from PySide2.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QPushButton
class MyWidget(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Vertical Layout Example")
self.setGeometry(300, 300, 400, 200)
# 创建 QVBoxLayout 对象
layout = QVBoxLayout()
layout.setSpacing(20) # 设置控件之间的间距
# 创建控件
label1 = QLabel("Label 1")
label2 = QLabel("Label 2")
button1 = QPushButton("Button 1")
button2 = QPushButton("Button 2")
# 将控件添加到布局中
layout.addWidget(label1)
layout.addWidget(label2)
layout.addWidget(button1)
layout.addWidget(button2)
# 设置布局为窗口的主布局
self.setLayout(layout)
if __name__ == "__main__":
app = QApplication(sys.argv)
widget = MyWidget()
widget.show()
sys.exit(app.exec_())
在上面的示例中,我们首先创建了一个 QVBoxLayout() 对象并将其设置为窗口的主布局。然后,我们使用 setSpacing() 方法设置了控件之间的间距为 20 像素。接下来,创建了两个 QLabel 和两个 QPushButton,并将它们添加到布局中。最后,将布局设置为窗口的主布局。
通过运行上述代码,您将看到一个带有间距的垂直布局的窗口,其中控件之间的间距为 20 像素。根据您的需要,您可以调整间距大小,以使您的布局更好地满足设计要求。
