【问题标题】:Python - PyQT4 how to detect the mouse click position anywhere in the window?Python - PyQT4 如何检测窗口中任意位置的鼠标点击位置?
【发布时间】:2013-11-18 11:47:03
【问题描述】:

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

【问题讨论】:

    标签: python qt user-interface pyqt pyqt4


    【解决方案1】:
    import sys
    from PyQt5 import QtWidgets, QtGui, QtCore
    
    class Example(QtWidgets.QMainWindow):
        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 = QtWidgets.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 main():
        app = QtWidgets.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)
    

    【讨论】:

    • 如何将 PyQt4.QtCore.QPoint 转换成原始数字?
    【解决方案2】:

    获取(x,y)坐标的另一种方式:

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

    【讨论】:

      猜你喜欢
      • 2011-11-08
      • 2014-10-19
      • 1970-01-01
      • 2012-06-13
      • 1970-01-01
      • 1970-01-01
      • 2018-08-10
      • 1970-01-01
      • 2015-04-04
      相关资源
      最近更新 更多