Python - PyQT4如何检测窗口中任何位置的鼠标点击位置?

时间:2013-11-07 00:21:00

标签: python qt user-interface pyqt pyqt4

我有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()

2 个答案:

答案 0 :(得分:11)

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()

<强>输出:

PyQt4.QtCore.QPoint(242, 285)
PyQt4.QtCore.QPoint(1741, 423)
PyQt4.QtCore.QPoint(439, 372)

答案 1 :(得分:2)

得到(x,y)坐标的另一种方法:

def mouseReleaseEvent(self, QMouseEvent):
    print('(', QMouseEvent.x(), ', ', QMouseEvent.y(), ')')