Reimplement event handler

Frequently used event handlers are often already created, such as:

Event Handler

Description

keyPressEvent

Works when you press the keyboard.

keyReleaseEvent

Works when you release the keyboard.

mouseDoubleClickEvent

Works when you double-click.

mouseMoveEvent

Works when you move the mouse.

mousePressEvent

Works when you press the mouse.

mouseReleaseEvent

Works when you release the mouse.

moveEvent

Works when the widget moves.

resizeEvent

Works when you resize the widget.


Let’s modify the keyPressEvent event handler to implement the ability to shut down, maximize, and adjust the size of the widget when a specific key is pressed.


Example

import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QWidget


class MyApp(QWidget):

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

        self.initUI()

    def initUI(self):

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

    def keyPressEvent(self, e):

        if e.key() == Qt.Key_Escape:
            self.close()
        elif e.key() == Qt.Key_F:
            self.showFullScreen()
        elif e.key() == Qt.Key_N:
            self.showNormal()


if __name__ == '__main__':

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

The event handler has been reimplemented so that clicking the ‘esc’ (escape), ‘F’ and ‘N’ makes the window close, maximize, or become average size.


Description

def keyPressEvent(self, e):

    if e.key() == Qt.Key_Escape:
        self.close()
    elif e.key() == Qt.Key_F:
        self.showFullScreen()
    elif e.key() == Qt.Key_N:
        self.showNormal()

The keyPressEvent event handler receives events from the keyboard as input.

e.key() restores which key has been pressed or released.

‘If you press the ‘esc’ key, the widget will exit through self.close().

If you press the ‘F’ or ‘N’ key, the widget will be maximized or back to its average size.

Prev/Next