原文: https://pythonspot.com/pyqt5-grid-layout/

PyQt5 支持网格布局,其名称为QGridLayout。 可以在水平和垂直方向上将小部件添加到网格中。 带有小部件的网格布局示例如下所示:

PyQt5 网格布局 - 图1

PyQt5 网格布局示例:

下面的示例创建网格:

  1. import sys
  2. from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QHBoxLayout, QGroupBox, QDialog, QVBoxLayout, QGridLayout
  3. from PyQt5.QtGui import QIcon
  4. from PyQt5.QtCore import pyqtSlot
  5. class App(QDialog):
  6. def __init__(self):
  7. super().__init__()
  8. self.title = 'PyQt5 layout - pythonspot.com'
  9. self.left = 10
  10. self.top = 10
  11. self.width = 320
  12. self.height = 100
  13. self.initUI()
  14. def initUI(self):
  15. self.setWindowTitle(self.title)
  16. self.setGeometry(self.left, self.top, self.width, self.height)
  17. self.createGridLayout()
  18. windowLayout = QVBoxLayout()
  19. windowLayout.addWidget(self.horizontalGroupBox)
  20. self.setLayout(windowLayout)
  21. self.show()
  22. def createGridLayout(self):
  23. self.horizontalGroupBox = QGroupBox("Grid")
  24. layout = QGridLayout()
  25. layout.setColumnStretch(1, 4)
  26. layout.setColumnStretch(2, 4)
  27. layout.addWidget(QPushButton('1'),0,0)
  28. layout.addWidget(QPushButton('2'),0,1)
  29. layout.addWidget(QPushButton('3'),0,2)
  30. layout.addWidget(QPushButton('4'),1,0)
  31. layout.addWidget(QPushButton('5'),1,1)
  32. layout.addWidget(QPushButton('6'),1,2)
  33. layout.addWidget(QPushButton('7'),2,0)
  34. layout.addWidget(QPushButton('8'),2,1)
  35. layout.addWidget(QPushButton('9'),2,2)
  36. self.horizontalGroupBox.setLayout(layout)
  37. if __name__ == '__main__':
  38. app = QApplication(sys.argv)
  39. ex = App()
  40. sys.exit(app.exec_())

解释

我们通过以下方式导入gridlayout和其他内容:

  1. from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QHBoxLayout, QGroupBox, QDialog, QVBoxLayout, QGridLayout

在方法createGridLayout()中,我们创建带有标题的网格并设置大小。

  1. def createGridLayout(self):
  2. self.horizontalGroupBox = QGroupBox("Grid")
  3. layout = QGridLayout()
  4. layout.setColumnStretch(1, 4)
  5. layout.setColumnStretch(2, 4)

使用addWidget

  1. layout.addWidget(Widget,X,Y)

最后,我们设置布局。

下载 PyQT5 示例