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
廣告
© . All rights reserved.