PyQt5:Graphicscene的所有项都具有坐标0.0

2024-06-01 02:09:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用了以下source并对其进行了一些修改,以获得以下小示例:

import sys
from PyQt5 import QtCore, QtWidgets

class GraphicsScene(QtWidgets.QGraphicsScene):
    def __init__(self):
        super(GraphicsScene, self).__init__()
        self.setSceneRect(0, 0, 600, 400)


    def mousePressEvent(self, event):
        if event.buttons() == QtCore.Qt.LeftButton:
            x = event.scenePos().x()
            y = event.scenePos().y()
            self.addRect(x, y, 100, 100)
        elif event.buttons() == QtCore.Qt.RightButton:
            for elem in self.items():
                print(elem.x())
        super(GraphicsScene, self).mousePressEvent(event)

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    scene = GraphicsScene()
    w = QtWidgets.QGraphicsView(scene)
    w.resize(610, 410)
    w.show()
    sys.exit(app.exec_())

其思想是,通过鼠标左键单击创建新的矩形(这已经起作用)并通过鼠标右键单击删除最近的矩形。我知道如何找到最近的矩形,但为此我需要现有矩形的坐标。如果将新矩形添加到场景中,我们将执行以下操作:

self.addRect(x, y, 100, 100)

但如果我迭代场景中的所有元素,并尝试使用以下方法获取元素的x坐标:

    for elem in self.items():
        print(elem.x())
        print(elem.pos().x())
        print(elem.scenePos().x())

然后所有打印输出都为零。我已经看过了docu,但据我所知,我正在做的正是docu建议的。你知道我做错了什么吗


编辑: 当然,我可以将所有坐标保存在一个附加列表中,使用该列表中的值计算最近的矩形,使用以下命令删除每个矩形:

    for elem in self.items():
        self.removeItem(elem)

并绘制剩余的矩形。但是,我希望有一个更干净的版本


Tags: inimportselfeventfordefsysitems
1条回答
网友
1楼 · 发布于 2024-06-01 02:09:21

作为documentation explains

Note that the item's geometry is provided in item coordinates, and its position is initialized to (0, 0). For example, if a QRect(50, 50, 100, 100) is added, its top-left corner will be at (50, 50) relative to the origin in the item's coordinate system.

因此有两种选择:

  • 添加具有指定大小但位于位置(0,0)的矩形,然后将其移动到所需位置:
    rectItem = self.addRect(0, 0, 100, 100)
    rectItem.setPos(x, y)
  • 使用addRect中的坐标并根据矩形的左上角获取实际位置:
    for elem in self.items():
        pos = elem.pos()
        if isinstance(elem, QtWidgets.QGraphicsRectItem):
            pos += elem.rect().topLeft()

相关问题 更多 >