PyQt - QGraphicsLayout



The QGraphicsLayout represents the class of layout that acts as a base class for all graphics views. This view can be used to create a large number of two-dimensional custom items. Typically, we can say it is an abstract class of Qt framework that uses virtual classes and method for arranging children within QGraphicsWidgets. The class QGraphicsWidgets is considered as the base class of all widget classes.

In context of QGraphicsLayout, each layout type uses its own specific class and method such as grid layout, anchor layout, and linear layout.

The QGraphicsLayout inherits from QGraphicsLayoutItem. As a result, this layout achieved through its own subclasses.

Custom Layout QGraphicsLayout

We can use QGraphicsLayout as a base class for creation of custom layout. However, this class uses its subclasses like QGraphicsLinearLayout or QGraphicsGridLayout.

Building a custom layout using various essential functions −

  • setGeometry() − This function notify when layout's geometry set.
  • sizeHint() − It provide the size hints for the layout.
  • count() − It returns the number of items present in the layout.
  • itemAt() − This function retrieve the items in the layout.
  • removeAt() − This function remove the item without destroying it.

Note that, we can write our own custom layout based on layout requirement and using classes with its method.

Example

Following example illustrate two rectangle in different position with its color using various classes and method of 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())

Output

The above code produces the following output −

qgraphicslayout
Advertisements