Python - PyQT4 如何检测窗口中任意位置的鼠标点击位置?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19825650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:43:41 来源:igfitidea点击:
Python - PyQT4 how to detect the mouse click position anywhere in the window?
提问by
I have 1024x768 resolution window, when there is a click or mouse over, i want to find the x, y values. How can i do that?
我有 1024x768 分辨率的窗口,当点击或鼠标悬停时,我想找到 x、y 值。我怎样才能做到这一点?
import sys
from PyQt4 import QtGui, QtCore
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
qbtn = QtGui.QPushButton('Quit', self)
#qbtn.clicked.connect(QtCore.QCoreApplication.instance().quit)
qbtn.clicked.connect(self.test)
qbtn.resize(qbtn.sizeHint())
qbtn.move(50, 50)
self.setGeometry(0, 0, 1024, 768)
self.setWindowTitle('Quit button')
self.setWindowFlags(self.windowFlags() | QtCore.Qt.FramelessWindowHint)
self.show()
def test(self):
print "show the position of mouse cursor in screen resolution: x is ?? , y is ??"
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
采纳答案by
import sys
from PyQt4 import QtGui, QtCore
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def mousePressEvent(self, QMouseEvent):
print QMouseEvent.pos()
def mouseReleaseEvent(self, QMouseEvent):
cursor =QtGui.QCursor()
print cursor.pos()
def initUI(self):
qbtn = QtGui.QPushButton('Quit', self)
qbtn.resize(qbtn.sizeHint())
qbtn.move(50, 50)
self.setGeometry(0, 0, 1024, 768)
self.setWindowTitle('Quit button')
self.setWindowFlags(self.windowFlags() | QtCore.Qt.FramelessWindowHint)
self.show()
def test(self):
print "test"
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Output:
输出:
PyQt4.QtCore.QPoint(242, 285)
PyQt4.QtCore.QPoint(1741, 423)
PyQt4.QtCore.QPoint(439, 372)
回答by Ayad B.S
The other way to get (x,y) coordinates:
获取 (x,y) 坐标的另一种方法:
def mouseReleaseEvent(self, QMouseEvent):
print('(', QMouseEvent.x(), ', ', QMouseEvent.y(), ')')