每当我尝试在场景中移动矩形时,矩形的原点似乎会更改为更新位置之前矩形所在的位置
因此,如果我在(0,0)处创建矩形并使用rect.setRect(x,y)移动它,那么返回位置将产生(0,0)而不是(x,y)
如果使用鼠标在Qgraphicscene中移动它,它将返回正确的(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)
看来我已经弄明白了
我将移动功能更改为以下内容:
这将为我返回场景中的正确位置! 无论如何,谢谢你:)
您忘记了图形项目的一个重要方面:它们的[场景]位置并不总是实际显示给用户的对象的左上角。 在使用
scene.add*()
添加项目时,这一点很清楚(这已在this question中进行了解释)。作为documentation explains:
项位置不是矩形位置,因此当您使用
setRect
时,您不会移动项,而是在指定位置设置新矩形,同时将项保留在其系统的(0,0)坐标处;注意,这也意味着如果该项没有父项,scenePos()
将与pos()
相同,否则它是相对于父项的如果要知道矩形左上角的实际位置,可以使用以下选项之一:
item.sceneBoundingRect().topLeft()
item.scenePos() + item.rect().topLeft()
如果总是在(0,0)处添加矩形,则可以只使用
setPos()
,但是如果需要基于当前实际矩形位置计算位置,则必须使用上述函数之一请注意,矩形的大小也可以为负数,因此如果需要可见矩形的左上角,则需要normalize它:
相关问题 更多 >
编程相关推荐