PyQt5学习4-布局管理

PyQt5中可以使用绝对定位和layout类来管理窗口中各个元素的大小和位置,常用的layout类,主要包含以下三种布局形式。

1
2
3
QHBoxLayout
QVBoxLayout
QGridLayout

QHBoxLayout

水平布局(horizontal)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#!/usr/bin/python3
#-*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QMessageBox, QPushButton, QHBoxLayout
class ex(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
layout = QHBoxLayout()
self.setLayout(layout)
self.names = ['About','Information','Question','Warning','Critical']
for name in self.names:
btn = QPushButton(name)
layout.addWidget(btn)
btn.clicked.connect(self.buttonClicked)
self.setWindowTitle('MessageBox Button')
self.show()
def buttonClicked(self):
text = self.sender().text()
if text == self.names[0]:
QMessageBox.about(self,'About', 'about this code')
elif text == self.names[1]:
QMessageBox.information(self,'Information', 'some information about this code')
elif text == self.names[2]:
QMessageBox.question(self,'Question', 'Is this helpful?')
elif text == self.names[3]:
QMessageBox.warning(self,'Warning', 'This is a warning!')
elif text == self.names[4]:
QMessageBox.critical(self,'Critical', 'This is an error!')
if __name__ == '__main__':
app = QApplication(sys.argv)
e = ex()
sys.exit(app.exec_())

该程序产生一个水平布局,结果如下

QHBoxLayout

QVBoxLayout

垂直布局(vertical)与水平布局类似,只需要把 QHBoxLayout 换成 QVBoxLayout。

QGridLayout

栅格布局(grid)将窗口划分为网格,可以在指定网格区间插入部件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#!/usr/bin/python3
#-*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QMessageBox, QPushButton, QGridLayout
class ex(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
layout = QGridLayout()
self.setLayout(layout)
for i in range(1,10):
for j in range(1,10):
btn_s = str(i)+'*'+str(j)
btn = QPushButton(btn_s)
layout.addWidget(btn,i,j)
btn.clicked.connect(self.buttonClicked)
self.setWindowTitle('MessageBox Button')
self.show()
def buttonClicked(self):
text = self.sender().text()
QMessageBox.information(self,'Results',str(eval(text)))
if __name__ == '__main__':
app = QApplication(sys.argv)
e = ex()
sys.exit(app.exec_())

该程序产生一个乘法表网格,结果如下

QGridLayout