布局控件
布局用处的介绍
常用的三种布局
- 垂直布局
- 水平布局
- 格子布局
项目:使用格子布局重新制作一个计算器
项目:重新制作进制转换器
其实还有一种布局QFormLayout但是后期开发用的比较少
from PySide6.QtWidgets import QApplication, QWidget, QVBoxLayout, QSlider, QLabel, QPushButton, QLineEdit, QHBoxLayoutclass MyWindow(QWidget):def __init__(self):super().__init__()# 登录页面self.mainLayout = QVBoxLayout() # 垂直布局self.userLayout = QHBoxLayout()self.userLayout.addWidget(QLabel('用户名'))self.userLayout.addWidget(QLineEdit())self.mainLayout.addLayout(self.userLayout)self.passwordLayout = QHBoxLayout()self.passwordLayout.addWidget(QLabel('密码'))self.passwordLayout.addWidget(QLineEdit())self.mainLayout.addLayout(self.passwordLayout)self.mainLayout.addWidget(QPushButton('登录'))self.setLayout(self.mainLayout)if __name__ == '__main__':app = QApplication([])try:window = MyWindow()window.show()except FileNotFoundError as e:print(e)except RuntimeError as e:print(f"Error loading UI: {e}")app.exec()
表单布局前期学习的时候会用的比较多
from PySide6.QtWidgets import QApplication, QWidget, QVBoxLayout, QSlider, QLabel, QPushButton, QLineEdit, QHBoxLayout, \QFormLayoutclass MyWindow(QWidget):def __init__(self):super().__init__()# 登录页面self.mainLayout = QVBoxLayout() # 垂直布局# self.userLayout = QHBoxLayout()# self.userLayout.addWidget(QLabel('用户名'))# self.userLayout.addWidget(QLineEdit())# self.mainLayout.addLayout(self.userLayout)## self.passwordLayout = QHBoxLayout()# self.passwordLayout.addWidget(QLabel('密码'))# self.passwordLayout.addWidget(QLineEdit())# self.mainLayout.addLayout(self.passwordLayout)self.formLayout = QFormLayout()self.formLayout.addRow('用户名',QLineEdit())self.formLayout.addRow('密码',QLineEdit())self.formLayout.addWidget(QPushButton('登录'))self.mainLayout.addLayout(self.formLayout)self.setLayout(self.mainLayout)if __name__ == '__main__':app = QApplication([])try:window = MyWindow()window.show()except FileNotFoundError as e:print(e)except RuntimeError as e:print(f"Error loading UI: {e}")app.exec()
格子布局
from PySide6.QtWidgets import QApplication, QWidget, QVBoxLayout, QSlider, QLabel, QPushButton, QLineEdit, QHBoxLayout, \QFormLayout, QGridLayoutclass MyWindow(QWidget):def __init__(self):super().__init__()# 登录页面self.mainLayout = QVBoxLayout() # 垂直控件self.gridLayout = QGridLayout() # 网格控件# self.gridLayout.addWidget(QPushButton('1'),0,0)# self.gridLayout.addWidget(QPushButton('2'),0,1)# self.gridLayout.addWidget(QPushButton('3'),0,2)# self.gridLayout.addWidget(QPushButton('4'),1,0,1,3) #1,3 一行 三列self.gridLayout.addWidget(QLabel('用户名'),0,0)self.gridLayout.addWidget(QLineEdit(),0,1)self.gridLayout.addWidget(QLabel('密码'),1,0)self.gridLayout.addWidget(QLineEdit(),1,1)self.gridLayout.addWidget(QPushButton('登录'),2,0,1,2)self.mainLayout.addLayout(self.gridLayout)self.setLayout(self.mainLayout)if __name__ == '__main__':app = QApplication([])try:window = MyWindow()window.show()except FileNotFoundError as e:print(e)except RuntimeError as e:print(f"Error loading UI: {e}")app.exec()