lang/pysideex/ MouseEventsExample001
This simply fills the window with a colour that is changed by clicking and dragging. It logs the mouse position and delta (x,y distance to point where mouse was pressed) to the console.
# widget that dumps mousemove events
import sys
from PySide6.QtCore import *
from PySide6.QtGui import *
from PySide6.QtWidgets import *
from PySide6.QtNetwork import *
def clamp(x,m,M):
if x < m:
return m
if x > M:
return M
return x
class MyWidget(QWidget):
def __init__(self,*xs,**kw):
self.h = 0
self.s = 255
self.v = 0
self.h0 = 0
self.v0 = 0
self.brush = QBrush()
self.brush.setColor(QColor.fromHsv(self.h,self.s,self.v))
super().__init__(*xs,**kw)
def mousePressEvent(self,event):
self.previous_pos = event.position().toPoint()
x0 = self.previous_pos.x()
y0 = self.previous_pos.y()
print(f"Press at ({x0},{y0})")
return super().mousePressEvent(event)
def mouseMoveEvent(self,event):
current_pos = event.position().toPoint()
x0 = self.previous_pos.x()
y0 = self.previous_pos.y()
x = current_pos.x()
y = current_pos.y()
dx = x - x0
dy = y - y0
self.h = (self.h0 + dx) % 360
self.v = clamp((self.v0 + dy),0,255)
self.brush.setColor(QColor.fromHsv(self.h,self.s,self.v))
print(f"Move ({x0},{y0}) => ({x},{y}) delta ({dx},{dy})")
self.update()
return super().mouseMoveEvent(event)
def mouseReleaseEvent(self, event) -> None:
current_pos = event.position().toPoint()
x0 = self.previous_pos.x()
y0 = self.previous_pos.y()
x = current_pos.x()
y = current_pos.y()
dx = x - x0
dy = y - y0
self.h0 = (self.h0 + dx) % 360
self.v0 = clamp((self.v0 + dy),0,255)
self.h = self.h0
self.v = self.v0
self.brush.setColor(QColor.fromHsv(self.h,self.s,self.v))
self.previous_pos = event.position().toPoint()
x0 = self.previous_pos.x()
y0 = self.previous_pos.y()
print(f"Release at ({x0},{y0})")
return super().mouseReleaseEvent(event)
def paintEvent(self, event) -> None:
with QPainter(self) as painter:
rect = self.rect()
print(f"rect {rect}")
painter.fillRect(rect,QColor.fromHsv(self.h,self.s,self.v))
return super().paintEvent(event)
app = QApplication(sys.argv)
win = QMainWindow()
w = MyWidget()
win.setCentralWidget(w)
win.show()
exit(app.exec())