【问题标题】:PyQT5 setRect moves origin point in a QGraphicsScenePyQT5 setRect 在 QGraphicsScene 中移动原点
【发布时间】:2020-09-29 13:49:36
【问题描述】:

每当我尝试在场景中移动矩形时,矩形的原点似乎会更改为矩形在更新位置之前所在的位置。

因此,如果我在 (0,0) 处创建矩形并使用 rect.setRect(x, y) 移动它,则返回该位置将产生 (0,0) 而不是 (x, y)。

如果您使用鼠标在 QGraphicsScene 中移动它,它将返回正确的 (x, y)。

我用来创建矩形的代码如下:

class placeableObject:
    def __init__(self, index, scene, QPen, QBrush, width=100, height=100):
        """Parent class for placeable objects"""
        self.width = float(width)
        self.height = float(height)
        self.index = index

        self.rect = scene.addRect(0, 0, int(width), int(height), QPen, QBrush)
        self.rect.setFlag(QtWidgets.QGraphicsItem.ItemIsMovable)

要移动这个矩形,我有以下嵌入函数和返回位置的函数:

def getPos(self):
    """Returns a list with the x,y position of the object in the scene"""
    return [self.rect.scenePos().x(), self.rect.scenePos().y()]

def move(self, x, y):
    """Moves the object in the editor view to coordinatex x,y"""
    self.rect.setRect(x, y, self.width, self.height)

【问题讨论】:

    标签: python pyqt5 qgraphicsscene


    【解决方案1】:

    您忘记了图形项目的一个重要方面:它们的 [场景] 位置并不总是实际显示给用户的对象的左上角。 使用scene.add*() 添加项目时这一点很清楚(这已经在this question 上解释过)。
    作为documentation explains

    请注意,项目的几何图形以项目坐标提供,其位置初始化为 (0, 0)。例如,如果添加了 QRect(50, 50, 100, 100),则其左上角相对于项目坐标系中的原点位于 (50, 50)。

    item 位置不是rectangle 位置,所以当你使用setRect 时你不是在移动item,而是在指定位置设置一个新的矩形,同时将项目留在其系统的 (0, 0) 坐标处;请注意,这也意味着如果项目没有父项,scenePos() 将与pos() 相同,否则它是相对于父项的。

    如果您想知道矩形左上角的实际位置,可以使用以下方法之一:

    • item.sceneBoundingRect().topLeft()
    • item.scenePos() + item.rect().topLeft()

    如果您总是在 (0, 0) 处添加矩形,那么您可以只使用 setPos(),但如果您需要根据当前的实际矩形位置计算位置,则必须使用上面的函数。

    注意矩形也可以有负尺寸,所以如果你需要可见矩形的左上角,你需要normalize它:

        item.scenePos() + item.rect().normalized().topLeft()
    

    【讨论】:

    • 这很有意义,感谢您的详细回答,这很有帮助!
    【解决方案2】:

    看来我已经想通了。

    我将移动功能更改为以下内容:

    def move(self, x, y):
        """Moves the object in the editor view to coordinatex x,y"""
        self.rect.setPos(x, y)
    

    这将为我返回场景中的正确位置! 无论如何谢谢:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-17
      • 2019-09-04
      • 1970-01-01
      相关资源
      最近更新 更多