Q_Chang
Q_Chang

Reputation: 409

How to get mouse release coordinates in QGraphicsView

Hi I'm new to Qt and pyside. I'm trying to get the coordinates of mouse in a QGraphicsView instance. I tried to reimplement my mouseReleaseEvent but wondering how would I actually use this reimplemented function.

In MainWindow class:

self.tScn = QtGui.QGraphicsScene()
self.graphicsView_2 = QtGui.QGraphicsView(self.centralwidget, self.tScn)

In MainConsumer class(derived from MainWindow:

def pointSelection(self):
    pos = self.tScn.mouseReleaseEvent(QMouseEvent)
    print(pos)

def mouseReleaseEvent(self, QMouseEvent):
    pos = QMouseEvent.lastScenePos()
    print(pos)
    return pos

python gives me this warning:

AttributeError: 'PySide.QtGui.QMouseEvent' object has no attribute 'lastScenePos'

I tried couple of different orders and structures but nothing worked and now I am really confused by the relationship between PySide.QtGui.QGraphicsScene.mouseReleaseEvent(event), PySide.QtGui.QGraphicsSceneMouseEvent.lastScenePos(), class PySide.QtGui.QGraphicsSceneMouseEvent([type=None]) and QtCore.QEvent.GraphicsSceneMouseRelease could somebody help me?

Thanks!

Upvotes: 1

Views: 1482

Answers (1)

finmor
finmor

Reputation: 451

Create a class that inherits from QGraphicsScene and has a signal like this

class MyGraphicsScene(QtGui.QGraphicsScene):
    signalMousePos = QtCore.pyqtSignal(QtCore.QPointF)
    def __init__(self, parent):
        super(MyGraphicsScene, self).__init__(parent)

and then override the mouseRelease event in this new class

def mouseReleaseEvent(QGraphicsSceneMouseEvent):
    pos = QGrapihcsSceneMouseEvent.lastScenePos()
    self.signalMousePos.emit(pos)

Then in your MainConsumer class replace

self.tScn = QtGui.QGraphicsScene()

with

self.tScn = MyQGraphicsScene()
self.tScn.signalMousePos.connect(self.pointSelection)

the pointSelection becomes

def pointSelection(self, pos)
    #Whatever you want to do with the position coordinates

and mouseReleaseEvent in MainConsumer is no longer necessary

Upvotes: 1

Related Questions