MousePressEvent,QGraphicsVi中的位置偏移

2024-06-25 05:48:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我对QGraphicsViewQGraphicsScene有一些困难。 当我缩放/取消缩放场景并使用mousePressEvent创建项目时,我在该位置有一个偏移量。如何避免这种情况?在

event.pos()似乎是个问题。。在

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()  

Tags: selfnoneeventinitdefsceneitemclass
1条回答
网友
1楼 · 发布于 2024-06-25 05:48:00

在场景而不是视图中重新实现mousePressEvent。在

这样,event参数将是一个^{},它有几个有用的附加函数——包括^{},它完全可以满足您的需要:

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)

相关问题 更多 >