Reimplemente event handler 2

This time, we will use mouseMoveEvent to track and print the position of the mouse.


Example

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


class MyApp(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):

        x = 0
        y = 0

        self.text = 'x: {0}, y: {1}'.format(x, y)
        self.label = QLabel(self.text, self)
        self.label.move(20, 20)

        self.setMouseTracking(True)

        self.setWindowTitle('Reimplementing event handler')
        self.setGeometry(300, 300, 300, 200)
        self.show()

    def mouseMoveEvent(self, e):

        x = e.x()
        y = e.y()

        text = 'x: {0}, y: {1}'.format(x, y)
        self.label.setText(text)
        self.label.adjustSize()


if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = MyApp()
    sys.exit(app.exec_())

Moving the mouse within the widget will result in an event and output the position of the mouse through the reimplemented event handler.


Description

self.text = 'x: {0}, y: {1}'.format(x, y)
self.label = QLabel(self.text, self)
self.label.move(20, 20)

Save the value of x, y as self.text and the text for self.label.

Move the position as much as x=20, y=20.


self.setMouseTracking(True)

Set setMouseTracking to True to track the mouse position.

Default is setMouseTracking (false), and mouseEvent occurs only when you click or release the mouse button.


def mouseMoveEvent(self, e):

    x = e.x()
    y = e.y()

    text = 'x: {0}, y: {1}'.format(x, y)
    self.label.setText(text)
    self.label.adjustSize()

Event e is an object that has information about the event. This event object depends on the type of event that is generated.

e.x(), e.y() restores the position of the mouse cursor when an event occurs within the widget.

If you set it to e.globalX(), e.globalY(), it will restore the position of the mouse cursor in the entire screen.

Use the self.label.adjustSize() method to automatically resize the label.


Results

../_images/6_4_reimplementing2_mac.png

Figure 7-4. Reimplement event handler 2.


Prev/Next