I recently created a program that will create QgraphicsEllipseItems whenever the mouse is clicked. That part works! However, it's not in the exact place where my cursor is. It seems to be slightly higher than where my mouse cursor is. I do have a QGraphicsRectItem created so maybe the two items are clashing with each other and moving off of one another? How can I get these circles to be placed on top of the rectangle item? Here's the code
class MyView(QtGui.QGraphicsView):
def __init__(self):
QtGui.QGraphicsView.__init__(self)
self.scene = QtGui.QGraphicsScene(self)
self.item = QtGui.QGraphicsRectItem(400, 400, 400, 400)
self.scene.addItem(self.item)
self.setScene(self.scene)
def paintMarkers(self):
self.cursor = QtGui.QCursor()
self.x = self.cursor.pos().x()
self.y = self.cursor.pos().y()
self.circleItem = QtGui.QGraphicsEllipseItem(self.x,self.y,10,10)
self.scene.addItem(self.circleItem)
self.circleItem.setPen(QtGui.QPen(QtCore.Qt.red, 1.5))
self.setScene(self.scene)
class Window(QtGui.QMainWindow):
def __init__(self):
#This initializes the main window or form
super(Window,self).__init__()
self.setGeometry(50,50,1000,1000)
self.setWindowTitle("Pre-Alignment system")
self.view = MyView()
self.setCentralWidget(self.view)
def mousePressEvent(self,QMouseEvent):
self.view.paintMarkers()
Much thanks!
There are two issues with the coordinates you are using to place the
QGraphics...Item
s. The first is that the coordinates fromQCursor
are global screen coordinates, so you need to useself.mapFromGlobal()
to convert them to coordinates relative to theQGraphicsView
.Secondly, you actually want the coordinates relative to the current
QGraphicsScene
, as this is where you are drawing the item. This is because the scene can be offset from the view (for example panning around a scene that is bigger than a view). To do this, you useself.mapToScene()
on the coordinates relative to theQGraphicsView
.I would point out that typically you would draw something on the
QGraphicsScene
in response to some sort of mouse event in theQGraphicsView
, which requires reimplementing things likeQGraphicsView.mouseMoveEvent
orQGraphicsView.mousePressEvent
. These event handlers are passed aQEvent
which contains the mouse coordinates relative to the view, and so you don't need to do the global coordinates transformation I mentioned in the first paragraph in these cases.Update
I've just seen your other question, and now understand some of the issue a bit better. You shouldn't be overriding the mouse event in the main window. Instead override it in the view. For example:
Here we have not needed to use
QWidget.mapFromGlobal()
(what I covered in the first paragraph) because we use a mouse event from theQGraphicsView
which returns coordinates relative to that widget only.Update 2
Note: I've updated how the item is created/placed in the above code based on this answer.