QLayout#
keywords: QLayout, Layout
Overview#
在 GUI 编程中, 一个很重要的概念就是 Layout, 也就是布局. 通过将 Widget 和 Layout 解耦和, 使得我们在编程时能一次只专注于一件事, 并且让整个代码的复用更加灵活. 展开来说就是你可以先专注于定义每个控件细节, 然后最后定义所有 Widget 之间的布局, 也就是 Layout. 如果你改变主意了, 你可以只改动你的 Layout 而不需要改变 Widget.
Examples#
QGridLayout_example.py
1# -*- coding: utf-8 -*-
2
3"""
4QGridLayout Example.
5"""
6
7import sys
8from PySide6 import QtWidgets
9
10
11class MainWidget(QtWidgets.QWidget):
12 def __init__(self, parent):
13 super().__init__(parent)
14 button1_wgt = QtWidgets.QPushButton("One")
15 button2_wgt = QtWidgets.QPushButton("Two")
16 button3_wgt = QtWidgets.QPushButton("Three")
17 button4_wgt = QtWidgets.QPushButton("Four")
18 button5_wgt = QtWidgets.QPushButton("Five")
19
20 main_lay = QtWidgets.QGridLayout(self)
21 main_lay.addWidget(button1_wgt, 0, 0)
22 main_lay.addWidget(button2_wgt, 0, 1)
23 main_lay.addWidget(
24 button3_wgt,
25 1, # row, start from 0
26 0, # column, start from 0
27 1, # rowSpan
28 2, # columnSpan
29 )
30 main_lay.addWidget(button4_wgt, 2, 0)
31 main_lay.addWidget(button5_wgt, 2, 1)
32
33 self.setLayout(main_lay)
34
35
36class MainWindow(QtWidgets.QMainWindow):
37 def __init__(self):
38 super().__init__()
39 self.main_wgt = MainWidget(self)
40 self.setCentralWidget(self.main_wgt)
41 self.setGeometry(
42 int(screen_width * 0.25), # x
43 int(screen_height * 0.25), # y
44 int(screen_width * 0.5), # w
45 int(screen_height * 0.5), # h
46 )
47 self.setWindowTitle("QGridLayout_example")
48 self.show()
49
50
51if __name__ == "__main__":
52 app = QtWidgets.QApplication(sys.argv)
53 screen_width, screen_height = app.screens()[0].size().toTuple()
54 main = MainWindow()
55 sys.exit(app.exec())
QFormLayout_example.py
1# -*- coding: utf-8 -*-
2
3"""
4QFormLayout Example.
5"""
6
7import sys
8from PySide6 import QtWidgets
9
10
11class MainWidget(QtWidgets.QWidget):
12 def __init__(self, parent):
13 super().__init__(parent)
14
15 main_lay_form = QtWidgets.QFormLayout(self)
16
17 main_lay_form.addRow(QtWidgets.QLabel("Firstname"), QtWidgets.QLineEdit())
18 main_lay_form.addRow(QtWidgets.QLabel("Lastname"), QtWidgets.QLineEdit())
19
20 age_input_box_wgt = QtWidgets.QSpinBox()
21 age_input_box_wgt.setMinimumWidth(
22 100, # minw
23 )
24 main_lay_form.addRow(QtWidgets.QLabel("Age"), age_input_box_wgt)
25
26 self.setLayout(main_lay_form)
27
28
29class MainWindow(QtWidgets.QMainWindow):
30 def __init__(self):
31 super().__init__()
32 self.main_wgt = MainWidget(self)
33 self.setCentralWidget(self.main_wgt)
34 self.setGeometry(
35 int(screen_width * 0.25), # x
36 int(screen_height * 0.25), # y
37 int(screen_width * 0.5), # w
38 int(screen_height * 0.5), # h
39 )
40 self.setWindowTitle("QFormLayout_example")
41 self.show()
42
43
44if __name__ == "__main__":
45 app = QtWidgets.QApplication(sys.argv)
46 screen_width, screen_height = app.screens()[0].size().toTuple()
47 main = MainWindow()
48 sys.exit(app.exec())
Reference#
Layout Management: Pyside6 中官方对于 Layout 的介绍.
Layout Classes: 列出了常用的 Layout 类的详细介绍.