from PyQt5.QtCore import QEvent from PyQt5.QtWidgets import QApplication, QWidget class MouseClickWidget(QWidget): def __init__(self): super().__init__() self.installEventFilter(self) def eventFilter(self, source, event): if event.type() == QEvent.MouseButtonPress: self.mousePressEvent() return True return super().eventFilter(source, event) def mousePressEvent(self): print("Mouse clicked") if __name__ == "__main__": app = QApplication.instance() or QApplication([]) widget = MouseClickWidget() widget.show() app.exec_()
from PyQt5.QtCore import QEvent, Qt, pyqtSignal from PyQt5.QtWidgets import QApplication, QLabel class KeyLabel(QLabel): key_pressed = pyqtSignal(int) def __init__(self, text): super().__init__(text) def keyPressEvent(self, event): self.key_pressed.emit(event.key()) super().keyPressEvent(event) if __name__ == "__main__": app = QApplication.instance() or QApplication([]) label = KeyLabel("Press any key...") label.key_pressed.connect(lambda key: print(f"Key pressed: {key}")) label.show() app.exec_()In both examples, we use the PyQt5 package library to handle events in a graphical user interface created using PyQt5.