PyQt5 布局
箱式布局(BoxLayout)
我们使用QHBoxLayout和QVBoxLayout,来分别创建水平布局和垂直布局。
import sys from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QHBoxLayout, QVBoxLayout class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): self.resize(250, 155) self.setWindowTitle('title') ok_button = QPushButton("OK") cancel_button = QPushButton("Cancel") hbox = QHBoxLayout() # 水平方向添加伸缩量 hbox.addStretch(1) # 水平布局里添加控件 hbox.addWidget(ok_button) hbox.addWidget(cancel_button) vbox = QVBoxLayout() # 垂直方向添加伸缩量 vbox.addStretch(1) # 垂直布局里添加水平布局 vbox.addLayout(hbox) # 设置窗口的布局 self.setLayout(vbox) self.show() if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_())
网格布局(QGridLayout)
网格布局将空间划分成若干行和若干列,使用QGridLayout类创建一个网格布局。
import sys from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QLineEdit, QTextEdit, QGridLayout class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): self.resize(250, 155) self.setWindowTitle('title') title = QLabel('Title') author = QLabel('Author') review = QLabel('Review') titleEdit = QLineEdit() authorEdit = QLineEdit() reviewEdit = QTextEdit() grid = QGridLayout() # 设置控件之间的间距 grid.setSpacing(10) grid.addWidget(title, 1, 0) grid.addWidget(titleEdit, 1, 1) grid.addWidget(author, 2, 0) grid.addWidget(authorEdit, 2, 1) grid.addWidget(review, 3, 0) # 控件跨度5行 grid.addWidget(reviewEdit, 3, 1, 5, 1) self.setLayout(grid) self.show() if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_())