PyQt5教程7:布局Layout管理

发布于:2022-12-29 ⋅ 阅读:(532) ⋅ 点赞:(0)

一、PyQt5的窗口布局

        布局管理是我们如何将小部件放置在应用程序窗口上的方式。我们可以使用绝对定位或布局类来放置我们的小部件。使用布局管理器管理布局是组织小部件的首选方式。

二、 绝对位置

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

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

以下示例以绝对坐标定位小部件。

absolute.py

#!/usr/bin/python

"""
ZetCode PyQt5 tutorial

This example shows three labels on a window
using absolute positioning.

Author: Jan Bodnar
Website: zetcode.com
"""

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()


def main():
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

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

lbl1 = QLabel('ZetCode', self)
lbl1.move(15, 10)

标签小部件位于 x=15 和 y=10。

三、用布局QHBoxLayout设定窗口位置

        QHBoxLayout 和 QVBoxLayout 是水平和垂直排列小部件的基本布局类。

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

box_layout.py

#!/usr/bin/python

"""
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
"""

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()


def main():
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

该示例在窗口的右下角放置了两个按钮。当我们调整应用程序窗口的大小时,它们会留在那里。我们同时使用 HBoxLayout 和 QVBoxLayout。

okButton = QPushButton("OK")
cancelButton = QPushButton("Cancel")

Here we create two push buttons.

hbox = QHBoxLayout()
hbox.addStretch(1)
hbox.addWidget(okButton)
hbox.addWidget(cancelButton)

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

vbox = QVBoxLayout()
vbox.addStretch(1)
vbox.addLayout(hbox)

        水平布局放置在垂直布局中。垂直框中的拉伸因子会将带有按钮的水平框推到窗口底部。self.setLayout(vbox)

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

四、网格式QGridLayout

        QGridLayout 是最通用的布局类。它将空间划分为行和列。

calculator.py

#!/usr/bin/python

"""
ZetCode PyQt5 tutorial

In this example, we create a skeleton
of a calculator using QGridLayout.

Author: Jan Bodnar
Website: zetcode.com
"""

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()


def main():
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

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

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 方法创建按钮并将其添加到布局中。

五、代码案例

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

review.py

#!/usr/bin/python

"""
ZetCode PyQt5 tutorial

In this example, we create a bit
more complicated window layout using
the QGridLayout manager.

Author: Jan Bodnar
Website: zetcode.com
"""

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()


def main():
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

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

grid = QGridLayout()
grid.setSpacing(10)

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

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

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


网站公告

今日签到

点亮在社区的每一天
去签到