如何理解垂直布局、水平布局和表单布局?
整体布局等于垂直布局或水平布局:
- 若将两个垂直布局添加进水平布局窗口内,则窗口整体呈水平布局展示
- 若将两个水平布局添加进垂直布局窗口内,则窗口整体呈垂直布局展示
1、垂直布局
- 设置窗口大小
- 四个按钮
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton
class winfom(QWidget):
def __init__(self):
super(winfom,self).__init__()
self.setWindowTitle("垂直布局管理")
self.resize(500,350)
# 垂直布局
vlayout = QVBoxLayout()
vlayout.addWidget(QPushButton(str(1)))
vlayout.addWidget(QPushButton(str(2)))
vlayout.addWidget(QPushButton(str(3)))
vlayout.addWidget(QPushButton(str(4)))
self.setLayout(vlayout)
if __name__ == '__main__':
app = QApplication(sys.argv)
form = winfom()
form.show()
sys.exit(app.exec_())
- 垂直布局示例图
2、水平布局
- QHBoxLayout
- 设置窗口大小
- 四个按钮即可
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton
class winfom(QWidget):
def __init__(self):
super(winfom,self).__init__()
self.setWindowTitle("水平布局管理")
self.resize(150,100)
# 水平布局
vlayout = QHBoxLayout()
vlayout.addWidget(QPushButton(str(1)))
vlayout.addWidget(QPushButton(str(2)))
vlayout.addWidget(QPushButton(str(3)))
vlayout.addWidget(QPushButton(str(4)))
self.setLayout(vlayout)
if __name__ == '__main__':
app = QApplication(sys.argv)
form = winfom()
form.show()
sys.exit(app.exec_())
- 水平布局示例图
- 在四个按钮上方,若加上vlayout.addStretch(0)
- 当你拉大窗口时,按钮会整体停留在窗口右侧
vlayout.addStretch(0)
vlayout.addWidget(QPushButton(str(1)))
vlayout.addWidget(QPushButton(str(2)))
vlayout.addWidget(QPushButton(str(3)))
vlayout.addWidget(QPushButton(str(4)))
- 在四个按钮下方,若加上vlayout.addStretch(0)
- 当你拉大窗口时,按钮会整体停留在窗口左侧
vlayout.addWidget(QPushButton(str(1)))
vlayout.addWidget(QPushButton(str(2)))
vlayout.addWidget(QPushButton(str(3)))
vlayout.addWidget(QPushButton(str(4)))
vlayout.addStretch(0)
- 垂直布局和水平布局的差别也就是一个字母的差别:垂直布局QVBoxLayout(V)和水平布局QHBoxLayout(H)的差别。
3、表单布局
- 设置表单对象
- 设置部件标签1、2、3
- 设置部件输入框1、2、3
- 添加相应部件标签和输入框即可。
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QFormLayout, QLabel, QLineEdit
class winfom(QWidget):
def __init__(self):
super(winfom,self).__init__()
self.setWindowTitle("表单布局")
self.resize(280,100)
# 表单布局
formlayout = QFormLayout()
lable1 = QLabel("标签1")
lineEdit1 = QLineEdit()
lable2 = QLabel("标签2")
lineEdit2 = QLineEdit()
lable3 = QLabel("标签3")
lineEdit3 = QLineEdit()
formlayout.addRow(lable1,lineEdit1)
formlayout.addRow(lable2,lineEdit2)
formlayout.addRow(lable3,lineEdit3)
self.setLayout(formlayout)
if __name__ == '__main__':
app = QApplication(sys.argv)
form = winfom()
form.show()
sys.exit(app.exec_())
- 表单布局示例图