如何在QGraphicsItem坐标系中获取光标点击位置?

问题描述 投票:2回答:1

我有一个加上QGraphicsSceneQGraphicsItem。假设我点击了绘制绿色圆圈的地图图像(QGraphicsItem)。如何根据这个QGraphicsItem而不是QGraphicsScene坐标系获得点击位置。

road_map

附:请不要使用鼠标事件处理编写代码。如何正确映射点击位置。提前致谢。

python python-3.x pyqt pyqt5 qgraphicsview
1个回答
2
投票

我们的想法是将相对于场景的坐标转换为相对于项目的坐标。

- Override mousePressEvent in QGraphicsScene:

使用QGraphicsItem的mapFromScene()方法:

from PyQt5 import QtCore, QtGui, QtWidgets
import random

class Scene(QtWidgets.QGraphicsScene):
    def __init__(self, parent=None):
        super(Scene, self).__init__(parent)
        pixmap = QtGui.QPixmap(100, 100)
        pixmap.fill(QtCore.Qt.red)

        self.pixmap_item = self.addPixmap(pixmap)
        # random position
        self.pixmap_item.setPos(*random.sample(range(-100, 100), 2))


    def mousePressEvent(self, event):
        items = self.items(event.scenePos())
        for item in items:
            if item is self.pixmap_item:
                print(item.mapFromScene(event.scenePos()))
        super(Scene, self).mousePressEvent(event)

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    scene = Scene()
    w = QtWidgets.QGraphicsView(scene)
    w.resize(640, 480)
    w.show()
    sys.exit(app.exec_())

- Override mousePressEvent in QGraphicsView:

使用QazraphicsItem的mapFromScene()方法与mapToScene()

from PyQt5 import QtCore, QtGui, QtWidgets
import random

class View(QtWidgets.QGraphicsView):
    def __init__(self, parent=None):
        super(View, self).__init__(QtWidgets.QGraphicsScene(), parent)
        pixmap = QtGui.QPixmap(100, 100)
        pixmap.fill(QtCore.Qt.red)

        self.pixmap_item = self.scene().addPixmap(pixmap)
        # random position
        self.pixmap_item.setPos(*random.sample(range(-100, 100), 2))


    def mousePressEvent(self, event):
        items = self.items(event.pos())
        for item in items:
            if item is self.pixmap_item:
                print(item.mapFromScene(self.mapToScene(event.pos())))
        super(View, self).mousePressEvent(event)

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = View()
    w.resize(640, 480)
    w.show()
    sys.exit(app.exec_())

- Override mousePressEvent of QGraphicsItem:

from PyQt5 import QtCore, QtGui, QtWidgets
import random

class PixmapItem(QtWidgets.QGraphicsPixmapItem):
    def mousePressEvent(self, event):
        print(event.pos())
        super(PixmapItem, self).mousePressEvent(event)

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    scene = QtWidgets.QGraphicsScene()
    w = QtWidgets.QGraphicsView(scene)
    pixmap = QtGui.QPixmap(100, 100)
    pixmap.fill(QtCore.Qt.red)
    item = PixmapItem(pixmap)
    scene.addItem(item)
    item.setPos(*random.sample(range(-100, 100), 2))
    w.resize(640, 480)
    w.show()
    sys.exit(app.exec_())
© www.soinside.com 2019 - 2024. All rights reserved.