PyQt5:为图形场景中的项目设置坐标

PyQt5: set coordinates for items in graphics scene

我有一个 scene = QGraphicsScene(),我通过 scene.addEllipse(100, 100, 10, 10, greenPen, greenBrush) 添加了一个椭圆。毛笔和笔都是事先准备好的。我在带有 MyGraphicsView.setScene(scene)QGraphicsView 之后添加了 QGraphicsScene。除了椭圆的位置始终是中心之外,所有这些都有效。 addEllipse() 函数中的前 2 个参数应该是坐标(在本例中为 100、100),但无论我放在那里什么,椭圆始终位于中心。有什么想法吗?

编辑:现在我添加了 3 个这样的省略号(删除了描述中的那个):

scene.addEllipse(10, 10, 10, 10, greenPen, greenBrush)
scene.addEllipse(-100, -10, 30, 30, bluePen, blueBrush)
scene.addEllipse(-100, -100, 60, 60, bluePen, blueBrush)

我的结果是这样的:

很明显,坐标以某种方式工作,但我仍然不明白究竟是如何工作的。我必须为场景设置原点吗?

如果我这样做:

particleList = scene.items()
print(particleList[0].x())
print(particleList[1].x())
print(particleList[2].x())

我得到:

0.0
0.0
0.0

此时我完全感到困惑,非常感谢您的帮助。

必须始终牢记的一件重要事情是 QGraphicsItem 的位置反映其“左上角”坐标。

事实上,您可以拥有一个 QGraphicsRectItem,其 QRectF 位于 (100, 100),但其位置位于 (50, 50)。这意味着矩形将 显示 在 (150, 150) 处。形状的位置相对于项目的位置

QGraphicsScene 的所有 add[Shape]() 函数在其文档中都有此重要说明:

Note that the item's geometry is provided in item coordinates, and its position is initialized to (0, 0).

即使您创建一个坐标为 (-100, -100) 的 QGraphicsEllipseItem,它仍将位于 (0, 0),这是因为 addEllipse() 中的值(与所有其他函数) 只描述 shape.

的坐标

然后,当创建一个QGraphicsScene时,它的sceneRect()没有明确设置,默认对应所有项的边界矩形。当场景添加到视图时,视图自动根据 alignment() 定位场景,默认为 Qt.AlignCenter:

If the whole scene is visible in the view, (i.e., there are no visible scroll bars,) the view's alignment will decide where the scene will be rendered in the view. For example, if the alignment is Qt::AlignCenter, which is default, the scene will be centered in the view, and if the alignment is (Qt::AlignLeft | Qt::AlignTop), the scene will be rendered in the top-left corner of the view.

这也意味着,如果您有项目处于负坐标或它们的 形状 处于负坐标,视图仍将显示以边界矩形中心为中心的场景全部 项。

所以,你要么根据需要设置场景sceneRect or the view sceneRect。如果未设置视图的 sceneRect,则默认为 scene 的 sceneRect。

如果要根据项目的位置显示项目,同时还要确保负坐标正确地位于中心“外部”,则必须决定 可见 sceneRect 和相应地设置它:

    boundingRect = scene.itemsBoundingRect()
    scene.setSceneRect(0, 0, boundingRect.right(), boundingRect.bottom())