Search code examples
qtpaintqgraphicsitemqgraphicsscene

Drawing Shapes within a QGraphicsItem (parent) with positions relative to the parent


I have my own object implementing a QGraphicsItem - it is essentially just a square with a border. I am attempting to draw shapes within that item, using it as the parent. The issue is that the coordinates I am using for the shapes within the parent are not relative to the parent's coordinates, but rather the scene.

Example: I want to draw a QGraphicsLineItem within my QGraphicsItem (the parent). The parent is at 50,50, with dimensions 20x20. If I draw a line with the parent specified, using coordinates 0,0,20,20, it draws at 0,0,20,20 relative to the scene, not the parent.

Is there a way to make the line (or any other shape) use positions relative the parent, not the scene? Or would I need to manually determine the coordinates by checking the parent's X and Y?


Solution

  • How about you make each of your QGraphicsItems also inherit from QObject, and pass a parent to each?.
    Then, determine the position in the scene based on the parent coords (recursive):

    class Scene(QGraphicsScene):
    
        def __init__(self):
            QGraphicsScene.__init__(self)
    
        def xpos(self):
            return 0
    
        def ypos(self):
            return 0
    
    
    class RelativeItem(QGraphicsRectItem, QObject):
    
        def __init__(self, parent):
            QGraphicsRectItem.__init__(self)
            QObject.__init__(self, parent)
    
        def xpos(self):
            return self.scenePos().x() - self.parent().xpos()
    
        def ypos(self):
            return self.scenePos().y() - self.parent().ypos()
    
    scene = QGraphicsScene()
    obj1 = RelativeItem(scene)  # Relative to scene
    obj2 = RelativeItem(obj1)  # Relative to obj1
    

    xpos() and ypos() recursively calls the parent's xpos() and ypos() (the scene is hard-coded at (0, 0)), and subtracts it from the object's position in the scene. This means that the two functions return the x and y positions of the object relative to the parent.