The Python Oracle

How to return mouse coordinates in realtime?

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game Looping

--

Chapters
00:00 How To Return Mouse Coordinates In Realtime?
00:38 Accepted Answer Score 9
01:03 Thank you

--

Full question
https://stackoverflow.com/questions/4168...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #python3x #pyqt #qt5 #pyqt5

#avk47



ACCEPTED ANSWER

Score 9


The QMouseEvent function must be implemented since it is executed when the mouse is moved.

import sys
from PyQt5.QtWidgets import (QApplication, QLabel, QWidget)


class MouseTracker(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
        self.setMouseTracking(True)

    def initUI(self):
        self.setGeometry(300, 300, 300, 200)
        self.setWindowTitle('Mouse Tracker')
        self.label = QLabel(self)
        self.label.resize(200, 40)
        self.show()

    def mouseMoveEvent(self, event):
        self.label.setText('Mouse coords: ( %d : %d )' % (event.x(), event.y()))


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MouseTracker()
    sys.exit(app.exec_())

enter image description here