PyQt - QVBoxLayout



The QVBoxLayout 类用于构建垂直方向的布局容器。容器中的内容会按照从上到下的顺序依次排列。可以使用各种 PyQt 函数创建垂直容器序列,例如 setLayout()、QPushButton()、addWidget()、addStretch()、setStyleSheet() 等。因此,所有这些函数对象都创建了一个活动的布局管理器。

qvboxlayout Ex Intro

QVBoxLayout 语法

构建垂直容器布局使用以下语法:

QVBoxLayout()

QVBoxLayout 在 PyQt 窗口中的用法

  • **垂直排列** - QVBoxLayout 是一种布局管理器,负责按垂直顺序排列小部件。
  • **动态调整大小** - 由于主窗口大小会发生变化,因此它是动态调整大小的。
  • **轻松添加小部件** - 我们可以使用 addWidget() 方法添加小部件。
  • **间距管理** - 可以通过 addStretch() 方法维护 QVBoxLayout 的间距。当需要留出空间时,可以使用此方法。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

示例 1

这里,我们创建一个使用 addWidget() 方法的 QVBoxLayout,并将按钮垂直显示。

from PyQt6.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout app = QApplication([]) window = QWidget() layout = QVBoxLayout() layout.addWidget(QPushButton('1')) layout.addWidget(QPushButton('2')) layout.addWidget(QPushButton('3')) window.setLayout(layout) window.show() app.exec()

输出

执行代码后,我们将获得以下输出:

qvboxlayout Ex Basic

示例 2

下面的示例演示了使用 QVBoxLayout 填充颜色后的垂直按钮。可以使用 QColor 类填充容器,该类提供内置函数 Color() 来设置颜色的名称。

import sys from PyQt6.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget from PyQt6.QtGui import QColor class Color(QWidget): def __init__(self, color): super().__init__() self.setAutoFillBackground(True) # default palette for current style palette = self.palette() # Modify the color palette.setColor(self.backgroundRole(), QColor(color)) self.setPalette(palette) class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() # Setting window title self.setWindowTitle("My App") layout = QVBoxLayout() layout.addWidget(Color('orange')) layout.addWidget(Color('blue')) layout.addWidget(Color('green')) widget = QWidget() widget.setLayout(layout) self.setCentralWidget(widget) if __name__ == "__main__": app = QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app.exec())

输出

执行代码后,我们将获得三个不同颜色的容器小部件:

qvboxlayout Ex One

示例 3

我们添加了 addStretch() 方法,该方法将按钮对齐到中心。这里,我们从开头到小部件(顶部)使用垂直间隔符,然后从小部件到结尾(底部)使用垂直间隔符。

import sys from PyQt6.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout class MainWindow(QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.setWindowTitle('PyQt QVBoxLayout') # create a layout layout = QVBoxLayout() self.setLayout(layout) # add a spacer layout.addStretch() # create buttons and add them to the layout title = ['A', 'B', 'C', 'D', 'E'] buttons = [QPushButton(t) for t in title] for button in buttons: layout.addWidget(button) # add a spacer layout.addStretch() # show the window self.show() if __name__ == '__main__': app = QApplication(sys.argv) window = MainWindow() sys.exit(app.exec())

输出

执行代码后,我们将获得以下结果:

qvboxlayout Ex Two
广告