Mouse Input
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel
from PyQt5.QtCore import Qt
class MouseDetectionApp(QMainWindow):
def __init__(self):
super(MouseDetectionApp, self).__init__()
self.label = QLabel(self)
self.label.setAlignment(Qt.AlignCenter)
self.label.setText("Click or move the mouse!")
self.label.setMouseTracking(True)
self.setCentralWidget(self.label)
self.init_ui()
def init_ui(self):
self.setWindowTitle('Mouse Event Detection')
self.setGeometry(100, 100, 400, 300)
def mousePressEvent(self, event):
self.label.setText("Mouse Pressed: Button {} at {}".format(event.button(), event.pos()))
def mouseReleaseEvent(self, event):
self.label.setText("Mouse Released: Button {} at {}".format(event.button(), event.pos()))
def mouseMoveEvent(self, event):
self.label.setText("Mouse Moved: Position {}".format(event.pos()))
def mouseDoubleClickEvent(self, event):
self.label.setText("Mouse Double Clicked: Button {} at {}".format(event.button(), event.pos()))
mousePressEvent(event): This method is called when a mouse button is pressed. It displays the pressed button and the position of the click.mouseReleaseEvent(event): Called when a mouse button is released. It displays the released button and its position.mouseMoveEvent(event): This is triggered when the mouse moves, displaying its current position.mouseDoubleClickEvent(event): Activated upon a mouse double click. It displays the button double clicked and its position.self.label.setMouseTracking(True): This line ensures that themouseMoveEventis invoked whenever the mouse is moved over the widget. IfsetMouseTrackingis set toFalse, themouseMoveEventis only invoked when a mouse button is pressed.event.button(): Returns information about the button (left, right, center) related to the mouse event.event.pos(): Returns the coordinate information where the mouse event occurred.