【问题标题】:Drawing Shapes within a QGraphicsItem (parent) with positions relative to the parent在 QGraphicsItem(父级)中绘制形状,其位置相对于父级
【发布时间】:2012-01-31 11:34:38
【问题描述】:

我有自己的对象实现QGraphicsItem - 它本质上只是一个带边框的正方形。我正在尝试在该项目中绘制形状,将其用作父项。问题是我用于父对象中的形状的坐标不是相对于父对象的坐标,而是相对于场景。

示例:我想在我的QGraphicsItem(父级)中绘制一个QGraphicsLineItem。父级为 50,50,尺寸为 20x20。如果我使用指定的父级绘制一条线,使用坐标 0,0,20,20,它会在相对于场景的 0,0,20,20 处绘制,而不是父级。

有没有办法让线条(或任何其他形状)使用相对于父级而不是场景的位置?或者我是否需要通过检查父母的 X 和 Y 来手动确定坐标?

【问题讨论】:

    标签: qt paint qgraphicsitem qgraphicsscene


    【解决方案1】:

    您如何让您的每个QGraphicsItems 也从QObject 继承,并将父级传递给每个?
    然后,根据父级坐标确定场景中的位置(递归):

    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()ypos() 递归调用父级的xpos()ypos()(场景硬编码在(0, 0)),并从场景中对象的位置中减去它。这意味着这两个函数返回对象相对于父对象的 x 和 y 位置。

    【讨论】:

    • 谢谢 - 这就是我打算做的事情。
    【解决方案2】:

    我唯一想到的是在设置子项绘图坐标之前在父项上使用QGraphicsItem::mapToScene

    【讨论】:

      【解决方案3】:

      您是否尝试过在设置QGraphicsLineItem 的位置时使用QGraphicsItem::setParentItem 并参考QGraphicsItem::parentItem

      【讨论】:

        猜你喜欢
        • 2021-12-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多