QGraphicsscene.itemAt() 方法抛出错误

QGraphicsscene.itemAt() method throws an error

我正在制作一个自定义场景,它将在 qgraphicsscene 中的鼠标位置打印项目。 但是,当我 运行 使用 cmd.

的代码时出现错误

这是完整的回溯

Traceback (most recent call last):
  File "filepath", line 10, in mousePressEvent
    print(self.itemAt(event.pos()))
TypeError: arguments did not match any overloaded call:
  itemAt(self, Union[QPointF, QPoint], QTransform): not enough arguments
  itemAt(self, float, float, QTransform): argument 1 has unexpected type 'QPointF'

这是代码。

import sys

from PyQt5 import QtWidgets, QtCore


class Scene(QtWidgets.QGraphicsScene):

    def mousePressEvent(self, event):
        # print(QtWidgets.QGraphicsView.mapToScene(event.pos()))
        print(self.itemAt(event.pos()))


def main():
    app = QtWidgets.QApplication(sys.argv)

    view = QtWidgets.QGraphicsView()
    scene = Scene()

    rect1 = QtWidgets.QGraphicsRectItem(QtCore.QRectF(20, 20, 100, 100))
    rect2 = QtWidgets.QGraphicsRectItem(QtCore.QRectF(20, 20, 100, 100))

    # rect1.setFlag(rect1.ItemIgnoresTransformations)
    # rect2.setFlag(rect2.ItemIgnoresTransformations)

    rect1.setFlag(rect1.ItemIsMovable)
    rect2.setFlag(rect2.ItemIsMovable)

    scene.addItem(rect1)
    scene.addItem(rect2)

    view.setScene(scene)
    view.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

我确实提到了一个类似的问题 但无法弄清楚如何正确使用此方法。请用更多的解释来回答这个问题。

(另外,请注意我确实尝试使用 event.pos().toPoint() 我得到了类似的错误)

正如回溯所说,您缺少 QTransform 参数,如 itemAt():

的参数签名所示

itemAt(const QPointF &position, const QTransform &deviceTransform)

如你所见,它们都是位置参数,没有 keyworded/default 参数。

因此,假设您没有使用任何转换,您必须至少添加一个新的 QTransform() 实例。请注意,在 QGraphicsSceneMouseEvent 的情况下,pos() 在项目坐标中,并且由于事件是在场景而不是项目上调用的,因此您需要使用 scenePos() 代替.

另请记住,为了根据您使用的 ItemIsMovable 标志正确允许项目移动,您还必须调用默认的基础实现。

    def mousePressEvent(self, event):
        print(self.itemAt(event.scenePos(), QtGui.QTransform()))
        super().mousePressEvent(event)