问题
Dragging, panning and mouse tracking items in Qt scene are the 3 actions which I want to simultaneously use in my app. However, it is more difficult than I thought.
Example code :
from PySide.QtCore import *
from PySide.QtGui import *
class View(QGraphicsView):
"""# HOW TO ATTACH MOUSE EVENTS PROGRAMMATICALLY ?
def mouseMoveEvent(self, event):
print "View MOVE", event.pos()
"""
class Scene(QGraphicsScene):
pass
class CircleForTrackingSwitch(QGraphicsEllipseItem):
def __init__(self, scene):
super(CircleForTrackingSwitch, self).__init__()
self.scene = scene
self.view = self.scene.views()[0]
self.setRect(QRect(20,20,20,20))
self.scene.addItem(self)
def mousePressEvent(self, event):
if self.view.hasMouseTracking() :
self.view.setMouseTracking(False)
else :
self.view.setMouseTracking(True)
print "Circle View SetTrack", event.pos()
def mouseMoveEvent(self, event):
print "Circle MOVE", event.pos()
class DraggableRectangle(QGraphicsRectItem):
def __init__(self, scene):
super(DraggableRectangle, self).__init__()
self.scene = scene
self.setRect(QRect(-20,-20,40,40))
self.scene.addItem(self)
#self.setFlag(QGraphicsItem.ItemIsMovable, True)
def mousePressEvent(self, event):
print "Rectangle PRESS", event.pos()
def mouseMoveEvent(self, event):
print "Rectangle MOVE", event.pos()
self.setPos(event.pos())
def mouseReleaseEvent(self, event):
print "Rectangle RELEASE", event.pos()
class Window(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.s = Scene()
self.s.setSceneRect(-200,-100,300,300,)
self.v = View(self.s)
self.v.setDragMode(QGraphicsView.ScrollHandDrag)
self.setCentralWidget(self.v)
CircleForTrackingSwitch(self.s)
DraggableRectangle(self.s)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
window = Window()
window.resize(300, 200)
window.show()
sys.exit(app.exec_())
MASTER QUESTION : How to attach mouse events programmatically? Many thanks.
回答1:
For the draggable Rectangle, since the Rectangle is already moveable, you only have to subclass it, to overload the different mouse functions (with the track stuff), then to call the parent's mouse event. Basically, you could have what you want with this rectangle class:
class DraggableRectangle(QGraphicsRectItem):
def __init__(self, scene, *args, **kwargs):
super().__init__(*args, **kwargs)
self.scene = scene
self.setRect(QRect(-20,-20,40,40))
self.scene.addItem(self)
self.setFlag(QGraphicsItem.ItemIsMovable, True) # Keep that
def mousePressEvent(self, event):
print "Rectangle PRESS", event.pos()
super().mousePressEvent(event) # Call parent
def mouseMoveEvent(self, event):
print "Rectangle MOVE", event.pos()
# Do not move by yourself
# Call parent that already handles the move
super().mouseMoveEvent(event)
def mouseReleaseEvent(self, event):
print "Rectangle RELEASE", event.pos()
super().mouseReleaseEvent(event) # Call parent
I hope this is what you were looking for.
来源:https://stackoverflow.com/questions/16221810/how-to-handle-mouse-events-in-qt