本文主要是了解视窗滑鼠事件
程式码:form_mouse_event.py
"""程式名称:form_mouse_event.py程式功能:1. 视窗滑鼠事件了解"""import sysfrom PySide6.QtCore import Qtfrom PySide6.QtWidgets import ( QWidget, QApplication)class MyApp(QWidget): def __init__(self): super().__init__() self.setWindowTitle('form_mouse_event.py') self.setGeometry(100, 100, 500, 300) #self.setMouseTracking(True) self.show() def leaveEvent(self, event): print('leaveEvent') def enterEvent(self, event): print('enterEvent') def mouseDoubleClickEvent(self, event): print('mouseDoubleClickEvent') def mousePressEvent(self, event): btn_event = event.button() match btn_event: case Qt.MouseButton.LeftButton: print('按了左键') case Qt.MouseButton.RightButton: print('按了右键') case Qt.MouseButton.MiddleButton: print('按了中键(滚轮)') case _: # 如电竞滑鼠或其它侧边也有按钮的滑鼠... # 因手边没有相关滑鼠, # 可能是Qt.MouseButton.ExtraButton(x),x为数字, # 要测试才知道。 print('按了滑鼠三键外的其它键') def mouseMoveEvent(self, event): print('mouseMoveEvent') def mouseReleaseEvent(self, event): print('mouseReleaseEvent') def wheelEvent(self, event): print('wheelEvent')if __name__ == '__main__': app = QApplication() my_app = MyApp() sys.exit(app.exec())
滑鼠移至视窗
enterEvent
滑鼠离开视窗
leaveEvent
说明:
所谓视窗区是指蓝色区块的区域。
滚轮滚动
只要滚动滚轮,会一直触发wheelEvent
滑鼠按键按下
在此以按滑鼠右键示範
按了右键(mousePressEvent)
mouseReleaseEvent
滑鼠按键双按
在此以按滑鼠左键示範
按了左键(mousePressEvent)
mouseReleaseEvent
mouseDoubleClickEvent
mouseReleaseEvent
说明:
那如何得知是按了哪个按键呢?
这时就要使用到PySide6.QtCore.Qt模组所提供的MouseButton列举(enum)
注:至于列举有哪些,可以参考连结:
PySide6.QtCore.Qt.MouseButton
于mousePressEvent事件,取出event.button()的值,在此判断是否为滑鼠常用的三个按键,判断LeftButton、RighttButton、MiddleButton三个列举值来进行列印输出。
在这边学习到一直期望很久的switch-case语法,在python语法为match-case(为何要跟其它语言不一样,XD~)。这语法要Python 3.10后才有。
其语法中,default的表示在Python中要用case _来表示。
滑鼠移动
当设定self.setMouseTracking(True)时,只要滑鼠在视窗移动,就会一直触发mouseMoveEvent
当设定self.setMouseTracking(False)或预设(没设定)时,滑鼠按下按键,移动滑鼠后才会触发mouseMoveEvent,因为有按了按键,故也会有mousePressEvent、mouseReleaseEvent事件。