对PyQt5的界面进行布局管理主要有两种方法,即采用绝对位置和布局类。在PyQt5中有四种布局方式,即水平布局、垂直布局、网格布局、表单布局,以及两种布局方法,即addLayout()和addWidget(),其中addLayout()用于在布局中插入子布局,addWidget()用于在布局中插入控件。
1. 在布局中添加其他布局
import sys from PyQt5.QtWidgets import QApplication, QWidget, QHBoxLayout, QVBoxLayout, QGridLayout, QFormLayout, QPushButton class MyWindow(QWidget): def __init__(self): super().__init__() self.setWindowTitle("嵌套布局示例") # 全局布局(2种):水平 wlayout = QHBoxLayout() # 局部布局(4种):水平、垂直、网格、表单 hlayout = QHBoxLayout() vlayout = QVBoxLayout() glayout = QGridLayout() flayout = QFormLayout() # 为局部布局添加控件(例如:按钮) hlayout.addWidget(QPushButton(str(1))) hlayout.addWidget(QPushButton(str(2))) vlayout.addWidget(QPushButton(str(3))) vlayout.addWidget(QPushButton(str(4))) glayout.addWidget(QPushButton(str(5)), 0, 0) glayout.addWidget(QPushButton(str(6)), 0, 1) glayout.addWidget(QPushButton(str(6)), 1, 0) glayout.addWidget(QPushButton(str(6)), 1, 1) flayout.addWidget(QPushButton(str(9))) flayout.addWidget(QPushButton(str(10))) flayout.addWidget(QPushButton(str(11))) flayout.addWidget(QPushButton(str(12))) # 准备4个控件 hwg = QWidget() vwg = QWidget() gwg = QWidget() fwg = QWidget() # 使用4个控件设置局部布局 hwg.setLayout(hlayout) vwg.setLayout(vlayout) gwg.setLayout(glayout) fwg.setLayout(flayout) # 将4个控件添加到全局布局中 wlayout.addWidget(hwg) wlayout.addWidget(vwg) wlayout.addWidget(gwg) wlayout.addWidget(fwg) # 将窗口本身设置为全局布局 self.setLayout(wlayout) if __name__ == "__main__": app = QApplication(sys.argv) win = MyWindow() win.show() sys.exit(app.exec_())
2. 在控件中添加布局
嵌套布局中一个缺点:4种局部布局需要4个空白控件;也可在一个空白控件中进行多种布局,从而实现相同的效果。
from PyQt5.QtWidgets import QWidget, QApplication, QHBoxLayout, QVBoxLayout, QGridLayout, QFormLayout, QPushButton import sys class MyWindow(QWidget): def __init__(self): super().__init__() self.setWindowTitle("嵌套布局示例") # 全局控件(注意参数self,用于“承载”全局布局) wwg = QWidget(self) # 全局布局(注意参数wwg) wl = QHBoxLayout(wwg) hlayout = QHBoxLayout() vlayout = QVBoxLayout() glayout = QGridLayout() flayout = QFormLayout() # 为局部布局添加控件(例如:按钮) hlayout.addWidget(QPushButton(str(1))) hlayout.addWidget(QPushButton(str(2))) vlayout.addWidget(QPushButton(str(3))) vlayout.addWidget(QPushButton(str(4))) glayout.addWidget(QPushButton(str(5)), 0, 0) glayout.addWidget(QPushButton(str(6)), 0, 1) glayout.addWidget(QPushButton(str(6)), 1, 0) glayout.addWidget(QPushButton(str(6)), 1, 1) flayout.addWidget(QPushButton(str(9))) flayout.addWidget(QPushButton(str(10))) flayout.addWidget(QPushButton(str(11))) flayout.addWidget(QPushButton(str(12))) # 这里在局部布局中添加控件,然后将其添加到全局布局中 wl.addLayout(hlayout) wl.addLayout(vlayout) wl.addLayout(glayout) wl.addLayout(flayout) if __name__ == "__main__": app = QApplication(sys.argv) win = MyWindow() win.show() sys.exit(app.exec_())