PyQt - QGraphicsLayout



QGraphicsLayout 代表了作为所有图形视图的基础类的布局类。此视图可用于创建大量二维自定义项。通常,我们可以说它是 Qt 框架的一个抽象类,它使用虚拟类和方法来排列 QGraphicsWidgets 内的子项。QGraphicsWidgets 类被认为是所有部件类的基类。

在 QGraphicsLayout 的上下文中,每种布局类型都使用其自己的特定类和方法,例如网格布局、锚布局和线性布局。

QGraphicsLayout 继承自 QGraphicsLayoutItem。因此,此布局通过其自己的子类实现。

自定义布局 QGraphicsLayout

我们可以使用 QGraphicsLayout 作为创建自定义布局的基类。但是,此类使用其子类,如 QGraphicsLinearLayout 或 QGraphicsGridLayout。

使用各种基本函数构建自定义布局 -

  • **setGeometry()** - 当布局的几何形状设置时,此函数会发出通知。
  • **sizeHint()** - 它为布局提供大小提示。
  • **count()** - 它返回布局中存在的项目数。
  • **itemAt()** - 此函数检索布局中的项目。
  • **removeAt()** - 此函数删除项目而不销毁它。

请注意,我们可以根据布局需求编写自己的自定义布局,并使用具有其方法的类。

示例

以下示例说明了使用 PyQt 的各种类和方法,在不同位置使用不同颜色的两个矩形。

import sys from PyQt6.QtCore import Qt from PyQt6.QtGui import QColor from PyQt6.QtWidgets import QApplication, QGraphicsRectItem, QGraphicsScene, QGraphicsView class CustomGraphicsItem(QGraphicsRectItem): def __init__(self, width, height, color): super().__init__() self.setRect(0, 0, width, height) self.setBrush(QColor(color)) if __name__ == "__main__": app = QApplication(sys.argv) scene = QGraphicsScene() view = QGraphicsView(scene) # Create custom graphics items box1 = CustomGraphicsItem(100, 50, "lightblue") box2 = CustomGraphicsItem(80, 30, "lightgreen") # Position the items box1.setPos(10, 10) box2.setPos(10, 70) # Add items to the scene scene.addItem(box1) scene.addItem(box2) view.show() sys.exit(app.exec())

输出

以上代码产生以下输出 -

qgraphicslayout
广告