[英]How to get correct mouse position in Python Qt5?
I'm trying to get correct mouse position in mouseReleaseEvent, but the mouse position I got is wrong.The ev.position() is not relative position on Widget.我试图在 mouseReleaseEvent 中获得正确的鼠标 position,但我得到的鼠标 position 是错误的。ev.position() 不是小部件上的相对 position。
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.pad = ChessPad()
w = QtWidgets.QWidget()
l = QtWidgets.QVBoxLayout()
w.setLayout(l)
l.addWidget(self.pad)
self.setCentralWidget(w)
class ChessPad(QtWidgets.QLabel):
def __init__(self):
super().__init__()
pad = QtGui.QPixmap(700, 300)
pad.fill(Qt.white)
self.setPixmap(pad)
def mouseReleaseEvent(self, ev):
ev_x = ev.position().x()
ev_y = ev.position().y()
print(ev_x, ev_y)
I get a workaround to solve this issue.我有一个解决方法来解决这个问题。 I add a label in vboxlayout, the ev.position() will return relative position.我在 vboxlayout 中添加了一个 label,ev.position() 将返回相对 position。
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.pad = ChessPad()
label = QtWidgets.QLabel("Chess Pad")
w = QtWidgets.QWidget()
l = QtWidgets.QVBoxLayout()
w.setLayout(l)
l.addWidget(label)
l.addWidget(self.pad)
self.setCentralWidget(w)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.