Reputation: 107
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_())
as you can see i am not able to move the rectangles and ellipses because of the mouse press event it is drawing a line
i want to be able to drag as well as draw a line
when pressed over graphics item it should drag other wise it should draw line
Upvotes: 1
Views: 244
Reputation: 29571
Use if itemAt(event.pos) is None:
in mousePressEvent()
to determine whether the click occurred over a QGraphicsItem
. Set a state flag self.__dragging = the_item
in that method, so that you can determine in the mouseMoveEvent()
and the mouseReleaseEvent()
whether you were dragging an object (self.__dragging is not None
) or drawing a line (self.__dragging is None
).
Upvotes: 1