如何在GraphicsItem上忽略mousePressEvent(PyQt4)

时间:2016-02-04 20:15:51

标签: python pyqt

     import sys 

from PyQt4 import QtGui,QtCore
x=-40
y=0
z=0
class MyView(QtGui.QGraphicsView):


    def __init__(self):
        QtGui.QGraphicsView.__init__(self)
        self.scene=QtGui.QGraphicsScene(self)
        self.item=[]
        self.item2=[]
        myLine=QtGui.QGraphicsLineItem(-10,20,20,20)
        myLine.setCursor(QtCore.Qt.CrossCursor)
        self.scene.addItem(myLine)
        myLine.setFlag(QtGui.QGraphicsItem.ItemIsMovable)

        self.setScene(self.scene)

    def keyPressEvent(self,event):
        global x
        global y
        global z
        if event.key()==QtCore.Qt.Key_Left:

            self.item.append(QtGui.QGraphicsRectItem(x,-10,40,40))
            self.scene.addItem(self.item[y])
            x=x+10
            self.item[y].setFlag(QtGui.QGraphicsItem.ItemIsMovable)
            y=y+1
        elif event.key()==QtCore.Qt.Key_Right:

            self.item2.append(QtGui.QGraphicsEllipseItem(x,-10,40,40))
            self.scene.addItem(self.item2[z])
            x=x+10
            self.item2[z].setFlag(QtGui.QGraphicsItem.ItemIsMovable)
            z=z+1
    def mousePressEvent(self , event):
        self._start=event.pos()
    def mouseReleaseEvent(self,event):
         start = QtCore.QPointF(self.mapToScene(self._start))
             end = QtCore.QPointF(self.mapToScene(event.pos()))
             self.scene.addItem(
                    QtGui.QGraphicsLineItem(QtCore.QLineF(start, end)))

if __name__=='__main__':
    app=QtGui.QApplication(sys.argv)
    view= MyView()
    view.show()
    sys.exit(app.exec_())

你可以看到我无法移动矩形和椭圆形因为鼠标按下事件它正在绘制一条线

我希望能够拖动以及画一条线

当按下图形项时,它应该拖动其他方式它应该画线

1 个答案:

答案 0 :(得分:1)

使用if itemAt(event.pos) is None:中的mousePressEvent()来确定点击是否发生在QGraphicsItem上。在该方法中设置状态标记self.__dragging = the_item,以便您可以在mouseMoveEvent()mouseReleaseEvent()中确定是拖动对象(self.__dragging is not None)还是绘制线条( self.__dragging is None)。