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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
import sys from PySide6.QtWidgets import QApplication, QMainWindow from PySide6.QtGui import QPainter, QMouseEvent, QPen, QColor class MainWindow(QMainWindow): def __init__(self): super().__init__() # 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)) painter.setPen(pen) # Draw line between each pair of mouse click positions for i in range(1, len(self.mouse_clicks)): painter.drawLine(self.mouse_clicks[i-1], self.mouse_clicks[i]) def mousePressEvent(self, event: QMouseEvent): # Get the mouse click position and add it to the list self.mouse_clicks.append(event.pos()) # Update drawing area self.update() def mouseReleaseEvent(self, event: QMouseEvent): # Get the mouse release position and add it to the list self.mouse_clicks.append(event.pos()) # Update the drawing area self.update() if __name__ == "__main__": # Create the application instance app = QApplication(sys.argv) # Create the main window instance window = MainWindow() # Show the window window.show() # Run the event loop sys.exit(app.exec()) |
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.