在一個GUI程序里,布局是一個很重要的方面。布局就是如何管理應用中的元素和窗口。有兩種方式可以搞定:絕對定位和PyQt5的layout類
絕對定位
每個程序都是以像素為單位區分元素的位置,衡量元素的大小。所以我們完全可以使用絕對定位搞定每個元素和窗口的位置。但是這也有局限性:
- 元素不會隨着我們更改窗口的位置和大小而變化。
- 不能適用於不同的平台和不同分辨率的顯示器
- 更改應用字體大小會破壞布局
- 如果我們決定重構這個應用,需要全部計算一下每個元素的位置和大小
下面這個就是絕對定位的應用

#!/usr/bin/python3 # -*- coding: utf-8 -*- """ ZetCode PyQt5 tutorial This example shows three labels on a window using absolute positioning. Author: Jan Bodnar Website: zetcode.com Last edited: August 2017 """ import sys from PyQt5.QtWidgets import QWidget, QLabel, QApplication class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): lbl1 = QLabel('Zetcode', self) lbl1.move(15, 10) lbl2 = QLabel('tutorials', self) lbl2.move(35, 40) lbl3 = QLabel('for programmers', self) lbl3.move(55, 70) self.setGeometry(300, 300, 250, 150) self.setWindowTitle('Absolute') self.show() if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_())
我們使用move()方法定位了每一個元素,使用x、y坐標。x、y坐標的原點是程序的左上角。
lbl1 = QLabel('Zetcode', self) lbl1.move(15, 10)
這個元素的左上角就在這個程序的左上角開始的(15, 10)的位置。
程序展示:
盒布局
使用盒布局能讓程序具有更強的適應性。這個才是布局一個應用的更合適的方式。QHBoxLayout
和QVBoxLayout
是基本的布局類,分別是水平布局和垂直布局。
如果我們需要把兩個按鈕放在程序的右下角,創建這樣的布局,我們只需要一個水平布局加一個垂直布局的盒子就可以了。再用彈性布局增加一點間隙。

#!/usr/bin/python3 # -*- coding: utf-8 -*- """ ZetCode PyQt5 tutorial In this example, we position two push buttons in the bottom-right corner of the window. Author: Jan Bodnar Website: zetcode.com Last edited: August 2017 """ import sys from PyQt5.QtWidgets import (QWidget, QPushButton, QHBoxLayout, QVBoxLayout, QApplication) class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): okButton = QPushButton("OK") cancelButton = QPushButton("Cancel") hbox = QHBoxLayout() hbox.addStretch(1) hbox.addWidget(okButton) hbox.addWidget(cancelButton) vbox = QVBoxLayout() vbox.addStretch(1) vbox.addLayout(hbox) self.setLayout(vbox) self.setGeometry(300, 300, 300, 150) self.setWindowTitle('Buttons') self.show() if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_())
上面的例子完成了在應用的右下角放了兩個按鈕的需求。當改變窗口大小的時候,它們能依然保持在相對的位置。我們同時使用了QHBoxLayout
和QVBoxLayout
。
okButton = QPushButton("OK") cancelButton = QPushButton("Cancel")
這是創建了兩個按鈕。
hbox = QHBoxLayout() hbox.addStretch(1) hbox.addWidget(okButton) hbox.addWidget(cancelButton)
創建一個水平布局,增加兩個按鈕和彈性空間。stretch函數在兩個按鈕前面增加了一些彈性空間。下一步我們把這些元素放在應用的右下角。
vbox = QVBoxLayout() vbox.addStretch(1) vbox.addLayout(hbox)
為了布局需要,我們把這個水平布局放到了一個垂直布局盒里面。彈性元素會把所有的元素一起都放置在應用的右下角。
self.setLayout(vbox)
最后,我們就得到了我們想要的布局。
程序預覽:
柵格布局
最常用的還是柵格布局了。這種布局是把窗口分為行和列。創建和使用柵格布局,需要使用QGridLayout模塊。

#!/usr/bin/python3 # -*- coding: utf-8 -*- """ ZetCode PyQt5 tutorial In this example, we create a skeleton of a calculator using a QGridLayout. author: Jan Bodnar website: zetcode.com last edited: January 2015 """ import sys from PyQt5.QtWidgets import (QWidget, QGridLayout, QPushButton, QApplication) class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): grid = QGridLayout() self.setLayout(grid) names = ['Cls', 'Bck', '', 'Close', '7', '8', '9', '/', '4', '5', '6', '*', '1', '2', '3', '-', '0', '.', '=', '+'] positions = [(i,j) for i in range(5) for j in range(4)] for position, name in zip(positions, names): if name == '': continue button = QPushButton(name) grid.addWidget(button, *position) self.move(300, 150) self.setWindowTitle('Calculator') self.show() if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_())
這個例子里,我們創建了柵格化的按鈕。
grid = QGridLayout()
self.setLayout(grid)
創建一個QGridLayout實例,並把它放到程序窗口里。
names = ['Cls', 'Bck', '', 'Close', '7', '8', '9', '/', '4', '5', '6', '*', '1', '2', '3', '-', '0', '.', '=', '+']
這是我們將要使用的按鈕的名稱。
positions = [(i,j) for i in range(5) for j in range(4)]
創建按鈕位置列表。
for position, name in zip(positions, names): if name == '': continue button = QPushButton(name) grid.addWidget(button, *position)
創建按鈕,並使用addWidget()
方法把按鈕放到布局里面。
程序預覽:
制作提交反饋信息的布局
組件能跨列和跨行展示,這個例子里,我們就試試這個功能。

#!/usr/bin/python3 # -*- coding: utf-8 -*- """ ZetCode PyQt5 tutorial In this example, we create a more complicated window layout using the QGridLayout manager. Author: Jan Bodnar Website: zetcode.com Last edited: August 2017 """ import sys from PyQt5.QtWidgets import (QWidget, QLabel, QLineEdit, QTextEdit, QGridLayout, QApplication) class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): 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) grid.addWidget(reviewEdit, 3, 1, 5, 1) self.setLayout(grid) self.setGeometry(300, 300, 350, 300) self.setWindowTitle('Review') self.show() if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_())
我們創建了一個有三個標簽的窗口。兩個行編輯和一個文版編輯,這是用QGridLayout
模塊搞定的。
grid = QGridLayout()
grid.setSpacing(10)
創建標簽之間的空間。
grid.addWidget(reviewEdit, 3, 1, 5, 1)
我們可以指定組件的跨行和跨列的大小。這里我們指定這個元素跨5行顯示。
程序預覽: