原文: http://zetcode.com/gui/pyqt4/layoutmanagement/

GUI 编程中的一个重要方面是布局管理。 布局管理是我们将小部件放置在窗口上的方式。 管理可以通过两种基本方式完成。 我们可以使用绝对定位或布局类。

绝对定位

程序员以像素为单位指定每个小部件的位置和大小。 使用绝对定位时,我们必须了解以下限制:

  • 如果我们调整窗口大小,则小部件的大小和位置不会改变
  • 在各种平台上,应用看起来可能有所不同
  • 在我们的应用中更改字体可能会破坏布局
  • 如果我们决定更改布局,则必须完全重做布局,这既繁琐又耗时

以下示例将小部件放置在绝对坐标中。

  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. """
  4. ZetCode PyQt4 tutorial
  5. This example shows three labels on a window
  6. using absolute positioning.
  7. author: Jan Bodnar
  8. website: zetcode.com
  9. last edited: October 2011
  10. """
  11. import sys
  12. from PyQt4 import QtGui
  13. class Example(QtGui.QWidget):
  14. def __init__(self):
  15. super(Example, self).__init__()
  16. self.initUI()
  17. def initUI(self):
  18. lbl1 = QtGui.QLabel('ZetCode', self)
  19. lbl1.move(15, 10)
  20. lbl2 = QtGui.QLabel('tutorials', self)
  21. lbl2.move(35, 40)
  22. lbl3 = QtGui.QLabel('for programmers', self)
  23. lbl3.move(55, 70)
  24. self.setGeometry(300, 300, 250, 150)
  25. self.setWindowTitle('Absolute')
  26. self.show()
  27. def main():
  28. app = QtGui.QApplication(sys.argv)
  29. ex = Example()
  30. sys.exit(app.exec_())
  31. if __name__ == '__main__':
  32. main()

我们使用move()方法定位小部件。 在我们的例子中,这些是标签。 我们通过提供 x 和 y 坐标来定位它们。 坐标系的起点在左上角。 x 值从左到右增长。 y 值从上到下增长。

  1. lbl1 = QtGui.QLabel('Zetcode', self)
  2. lbl1.move(15, 10)

标签窗口小部件位于x=15y=10处。

PyQt4 中的布局管理 - 图1

图:绝对定位

盒子布局

具有布局类的布局管理更加灵活和实用。 这是在窗口上放置小部件的首选方法。 QtGui.QHBoxLayoutQtGui.QVBoxLayout是基本的布局类,可水平和垂直排列小部件。

想象一下,我们想在右下角放置两个按钮。 为了创建这样的布局,我们将使用一个水平框和一个垂直框。 为了创建必要的空间,我们将添加拉伸因子。

  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. """
  4. ZetCode PyQt4 tutorial
  5. In this example, we position two push
  6. buttons in the bottom-right corner
  7. of the window.
  8. author: Jan Bodnar
  9. website: zetcode.com
  10. last edited: October 2011
  11. """
  12. import sys
  13. from PyQt4 import QtGui
  14. class Example(QtGui.QWidget):
  15. def __init__(self):
  16. super(Example, self).__init__()
  17. self.initUI()
  18. def initUI(self):
  19. okButton = QtGui.QPushButton("OK")
  20. cancelButton = QtGui.QPushButton("Cancel")
  21. hbox = QtGui.QHBoxLayout()
  22. hbox.addStretch(1)
  23. hbox.addWidget(okButton)
  24. hbox.addWidget(cancelButton)
  25. vbox = QtGui.QVBoxLayout()
  26. vbox.addStretch(1)
  27. vbox.addLayout(hbox)
  28. self.setLayout(vbox)
  29. self.setGeometry(300, 300, 300, 150)
  30. self.setWindowTitle('Buttons')
  31. self.show()
  32. def main():
  33. app = QtGui.QApplication(sys.argv)
  34. ex = Example()
  35. sys.exit(app.exec_())
  36. if __name__ == '__main__':
  37. main()

该示例在窗口的右下角放置了两个按钮。 当我们调整应用窗口的大小时,它们会停留在该位置。 我们同时使用QtGui.HBoxLayoutQtGui.QVBoxLayout

  1. okButton = QtGui.QPushButton("OK")
  2. cancelButton = QtGui.QPushButton("Cancel")

在这里,我们创建两个按钮。

  1. hbox = QtGui.QHBoxLayout()
  2. hbox.addStretch(1)
  3. hbox.addWidget(okButton)
  4. hbox.addWidget(cancelButton)

我们创建一个水平框布局,并添加一个拉伸因子和两个按钮。 拉伸在两个按钮之前增加了可拉伸的空间。 这会将它们推到窗口的右侧。

  1. vbox = QtGui.QVBoxLayout()
  2. vbox.addStretch(1)
  3. vbox.addLayout(hbox)

为了创建必要的布局,我们将水平布局放入垂直布局。 垂直框中的拉伸因子会将带有按钮的水平框推到窗口底部。

  1. self.setLayout(vbox)

最后,我们设置窗口的主要布局。

PyQt4 中的布局管理 - 图2

图:按钮

QtGui.QGridLayout

最通用的布局类是网格布局。 此布局将空间分为行和列。 要创建网格布局,我们使用QtGui.QGridLayout类。

  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. import sys
  4. from PyQt4 import QtGui
  5. """
  6. ZetCode PyQt4 tutorial
  7. In this example, we create a skeleton
  8. of a calculator using a QtGui.QGridLayout.
  9. author: Jan Bodnar
  10. website: zetcode.com
  11. last edited: July 2014
  12. """
  13. class Example(QtGui.QWidget):
  14. def __init__(self):
  15. super(Example, self).__init__()
  16. self.initUI()
  17. def initUI(self):
  18. grid = QtGui.QGridLayout()
  19. self.setLayout(grid)
  20. names = ['Cls', 'Bck', '', 'Close',
  21. '7', '8', '9', '/',
  22. '4', '5', '6', '*',
  23. '1', '2', '3', '-',
  24. '0', '.', '=', '+']
  25. positions = [(i,j) for i in range(5) for j in range(4)]
  26. for position, name in zip(positions, names):
  27. if name == '':
  28. continue
  29. button = QtGui.QPushButton(name)
  30. grid.addWidget(button, *position)
  31. self.move(300, 150)
  32. self.setWindowTitle('Calculator')
  33. self.show()
  34. def main():
  35. app = QtGui.QApplication(sys.argv)
  36. ex = Example()
  37. sys.exit(app.exec_())
  38. if __name__ == '__main__':
  39. main()

在我们的示例中,我们创建了一个按钮网格。

  1. grid = QtGui.QGridLayout()
  2. self.setLayout(grid)

创建QtGui.QGridLayout的实例,并将其设置为应用窗口的布局。

  1. names = ['Cls', 'Bck', '', 'Close',
  2. '7', '8', '9', '/',
  3. '4', '5', '6', '*',
  4. '1', '2', '3', '-',
  5. '0', '.', '=', '+']

这些是稍后用于按钮的标签。

  1. positions = [(i,j) for i in range(5) for j in range(4)]

我们在网格中创建位置列表。

  1. for position, name in zip(positions, names):
  2. if name == '':
  3. continue
  4. button = QtGui.QPushButton(name)
  5. grid.addWidget(button, *position)

使用addWidget()方法创建按钮并将其添加到布局。

PyQt4 中的布局管理 - 图3

图:计算机骨架

回顾示例

小部件可以跨越网格中的多个列或行。 在下一个示例中,我们将对此进行说明。

  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. """
  4. ZetCode PyQt4 tutorial
  5. In this example, we create a bit
  6. more complicated window layout using
  7. the QtGui.QGridLayout manager.
  8. author: Jan Bodnar
  9. website: zetcode.com
  10. last edited: October 2011
  11. """
  12. import sys
  13. from PyQt4 import QtGui
  14. class Example(QtGui.QWidget):
  15. def __init__(self):
  16. super(Example, self).__init__()
  17. self.initUI()
  18. def initUI(self):
  19. title = QtGui.QLabel('Title')
  20. author = QtGui.QLabel('Author')
  21. review = QtGui.QLabel('Review')
  22. titleEdit = QtGui.QLineEdit()
  23. authorEdit = QtGui.QLineEdit()
  24. reviewEdit = QtGui.QTextEdit()
  25. grid = QtGui.QGridLayout()
  26. grid.setSpacing(10)
  27. grid.addWidget(title, 1, 0)
  28. grid.addWidget(titleEdit, 1, 1)
  29. grid.addWidget(author, 2, 0)
  30. grid.addWidget(authorEdit, 2, 1)
  31. grid.addWidget(review, 3, 0)
  32. grid.addWidget(reviewEdit, 3, 1, 5, 1)
  33. self.setLayout(grid)
  34. self.setGeometry(300, 300, 350, 300)
  35. self.setWindowTitle('Review')
  36. self.show()
  37. def main():
  38. app = QtGui.QApplication(sys.argv)
  39. ex = Example()
  40. sys.exit(app.exec_())
  41. if __name__ == '__main__':
  42. main()

我们创建一个窗口,其中有三个标签,两个行编辑和一个文本编辑小部件。 使用QtGui.QGridLayout完成布局。

  1. grid = QtGui.QGridLayout()
  2. grid.setSpacing(10)

我们创建网格布局并设置小部件之间的间距。

  1. grid.addWidget(reviewEdit, 3, 1, 5, 1)

如果我们将小部件添加到网格,则可以提供小部件的行跨度和列跨度。 在我们的例子中,我们使reviewEdit小部件跨越 5 行。

PyQt4 中的布局管理 - 图4

图:回顾 example

PyQt4 教程的这一部分专门用于布局管理。