在 PyQt5 中,可以使用 QGridLayout 布局来实现控件的自动排列。对于中心控件位置的问题,可以通过将控件添加到 QGridLayout 布局中心位置的方法来解决。
示例代码:
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QGridLayout, QLabel
class MyWidget(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
gridLayout = QGridLayout()
label1 = QLabel('Label 1', self)
label2 = QLabel('Label 2', self)
gridLayout.addWidget(label1, 0, 0)
gridLayout.addWidget(label2, 1, 1)
# 设置第 3 行、第 3 列为中心位置
gridLayout.setRowStretch(2, 1)
gridLayout.setColumnStretch(2, 1)
self.setLayout(gridLayout)
self.setGeometry(300, 300, 300, 200)
self.setWindowTitle('Central widget position of layout')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
widget = MyWidget()
sys.exit(app.exec_())
此例中,将 label1 和 label2 控件添加到了 (0,0) 和 (1,1) 的位置。同时,将第 3 行和第 3 列的比例设为 1,即使控件占据中心位置。运行程序后,可以看到 label2 控件已经占据了中心位置。
上一篇:布局的位置不正确。