Trying to get just “x” coordinate from pos() metho

2019-09-02 08:18发布

I'm currently having an issue getting just the x position of the cursor so I can place a marker on that x and y location. I'm using QGraphicsScene and view to create this circle object at the location of the mouse when the mouse is clicked. Since the QGraphicsEllipseItem takes 4 arguments it seems I need the x and y coordinate separate not just what the position method gives you since it gives both x and y. How do I split the two coordinates up? Here's the code:

import sys
from PyQt4 import QtGui, QtCore    

def paintMarkers(self):
    self.cursor = QtGui.QCursor()
    self.x,y = self.cursor.pos()
    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)

def mousePressEvent(self,QMouseEvent):
    self.view.paintMarkers()

Much thanks!

1条回答
姐就是有狂的资本
2楼-- · 2019-09-02 08:54

I'm not 100% clear what your problem is (are you getting an exception? Does it run but you get unexpected output?), but this line looks like the culprit:

self.x,y = self.cursor.pos()

This will create x as an attribute of self, and then create a local variable y that has no association with self at all. If you want both of them to be attributes of self, do

self.x, self.y = self.cursor.pos()

If you were getting an error while trying to do QGraphicsEllipseItem(self.x,self.y,10,10), this would explain why - self.y didn't exist, so it would give you an AttributeError.

查看更多
登录 后发表回答