arcane9
arcane9

Reputation: 53

pyQt4 QGraphicsView on mouse event help needed

I have done a fair amount of searching for this problem, which is probably trivial. However I am new to pyQT and am completely stuck. Any help would be appreciated.

I simply want to place, move and draw objects on a QGraphicsView widget using QGraphicsScene. The following code to handle mouse press events works, but it fires when the mouse is clicked anywhere in the form and not just in the QGraphicViewer (also as the result of this the object is subsequently placed in the wrong place). Here is an extract from the code I'm using now

def mousePressEvent(self, ev): #QGraphicsSceneMouseEvent
    if ev.button()==Qt.LeftButton:
        item = QGraphicsTextItem("CLICK")
        item.setPos(ev.x(), ev.y())
        #item.setPos(ev.scenePos())
        self.scene.addItem(item)

I know I should be using the QGraphicsSceneMouseEvent and I can see how this is implemented in C++; but I have no idea how to get this to work in Python.

Thanks

Upvotes: 5

Views: 3502

Answers (1)

Eryk Sun
Eryk Sun

Reputation: 34270

Try extending QtGui.QGraphicsScene and using its mousePressEvent and the coordinates from scenePos(). Something like:

class QScene(QtGui.QGraphicsScene):
    def __init__(self, *args, **kwds):
        QtGui.QGraphicsScene.__init__(self, *args, **kwds)

    def mousePressEvent(self, ev):
        if ev.button() == QtCore.Qt.LeftButton:
            item = QtGui.QGraphicsTextItem("CLICK")
            item.setPos(ev.scenePos())
            self.addItem(item)

Upvotes: 6

Related Questions