Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pyQt4 QGraphicsView on mouse event help needed

Tags:

python

qt

pyqt

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

like image 455
arcane9 Avatar asked Jul 24 '11 02:07

arcane9


1 Answers

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)
like image 99
Eryk Sun Avatar answered Nov 10 '22 00:11

Eryk Sun