In this Python PySide6 lesson we want to learn about Python PySide6 Mouse Events, In PySide6 you can handle mouse press and release events using the mousePressEvent and mouseReleaseEvent functions. these functions are part of the QWidget class and can be overridden in your custom widget class to handle mouse events.
This is an example of how to use mousePressEvent and mouseReleaseEvent in PySide6:
from PySide6.QtWidgets import QApplication, QMainWindow
from PySide6.QtGui import QPainter, QMouseEvent, QPen, QColor
# Set the window properties
self.setWindowTitle("Mouse Press - GeekCoders.com")
self.setGeometry(100, 100, 800, 600)
# Create list to store the mouse click positions
self.mouse_clicks = 
def paintEvent(self, event):
# Create QPainter object
painter = QPainter(self)
# Set pen color to red
pen = QPen(QColor(255, 0, 0))
# Draw line between each pair of mouse click positions
for i in range(1, len(self.mouse_clicks)):
def mousePressEvent(self, event: QMouseEvent):
# Get the mouse click position and add it to the list
# Update drawing area
def mouseReleaseEvent(self, event: QMouseEvent):
# Get the mouse release position and add it to the list
# Update the drawing area
if __name__ == "__main__":
# Create the application instance
app = QApplication(sys.argv)
# Create the main window instance
window = MainWindow()
# Show the window
# Run the event loop
In this example we have created custom widget MyWidget that responds to mouse press and release events. the paintEvent function draws line between the start and end positions using the QPainter class. mousePressEvent function sets the start_pos variable to the position of the left mouse button press. mouseReleaseEvent function sets the end_pos variable to the position of the left mouse button release and calls the update function to trigger a repaint.
Note that we check for the left mouse button using event.button() == Qt.LeftButton. you can also check for the right mouse button using Qt.RightButton or the middle mouse button using Qt.MiddleButton.
Overall PySide6 makes it easy to handle mouse press and release events in your custom widgets, allowing you to create interactive and responsive UI elements.
Run the complete code press the mouse button and this will be the result.