2012-09-03 6 views
7

QGraphicsViewQGraphicsScene과 관련된 몇 가지 어려움이 있습니다. 장면을 확대/축소하고 mousePressEvent로 항목을 만들 때 위치에 오프셋이 있습니다. 어떻게 피할 수 있습니까? MousePressEvent, QGraphicsView의 위치 오프셋

event.pos()

오히려보기보다, 현장에 구현할 mousePressEvent 있습니다 .. 문제

from PyQt4 import QtCore, QtGui 

class graphicsItem (QtGui.QGraphicsItem): 
    def __init__ (self): 
     super(graphicsItem, self).__init__() 
     self.rectF = QtCore.QRectF(0,0,10,10) 
    def boundingRect (self): 
     return self.rectF 
    def paint (self, painter=None, style=None, widget=None): 
     painter.fillRect(self.rectF, QtCore.Qt.red) 

class graphicsScene (QtGui.QGraphicsScene): 
    def __init__ (self, parent=None): 
     super (graphicsScene, self).__init__ (parent) 

class graphicsView (QtGui.QGraphicsView): 
    def __init__ (self, parent = None): 
     super (graphicsView, self).__init__ (parent) 
     self.parent = parent 
    def mousePressEvent(self, event): 
     super (graphicsView, self).mousePressEvent(event) 
     item = graphicsItem() 
     position = QtCore.QPointF(event.pos()) - item.rectF.center() 
     item.setPos(position.x() , position.y()) 
     self.parent.scene.addItem(item) 
    def wheelEvent (self, event): 
     super (graphicsView, self).wheelEvent(event) 
     factor = 1.2 
     if event.delta() < 0 : 
      factor = 1.0/factor 
     self.scale(factor, factor) 

class window (QtGui.QMainWindow): 
    def __init__ (self, parent = None) : 
     super (window, self).__init__(parent) 
     self.width = 800 
     self.height = 600 

     self.resize(self.width,self.height) 
     self.mainLayout = QtGui.QVBoxLayout(self) 

     self.view = graphicsView(self) 
     self.scene = graphicsScene(self) 
     self.view.setScene (self.scene) 

     factor = 1 
     self.scene.setSceneRect(0, 0, self.width * factor, self.height * factor) 
     self.view.setMinimumSize(self.width, self.height) 

     self.mainLayout.addWidget(self.view) 

    def show (self): 
     super (window, self).show() 

답변

6

을 보인다.

그 방법의 event 인수는 몇 가지 유용한 추가 기능이있는 QGraphicsSceneMouseEvent이 될 것입니다 - 당신이 원하는 것을 정확히 수행 scenePos을 포함하여 :

class graphicsScene(QtGui.QGraphicsScene): 
    def __init__ (self, parent=None): 
     super(graphicsScene, self).__init__ (parent) 

    def mousePressEvent(self, event): 
     super(graphicsScene, self).mousePressEvent(event) 
     item = graphicsItem() 
     position = QtCore.QPointF(event.scenePos()) - item.rectF.center() 
     item.setPos(position.x() , position.y()) 
     self.addItem(item) 
+1

나는이 솔루션을 좋아하고 그것을 자신을 사용합니다. 그것은 내부적으로 그래픽보기에서 mousePressEvent를 가졌고 마우스 위치를 mapToScene과 비슷합니다. 그러나 이것은 더 우아합니다. – Trilarion

관련 문제