在QWidget和QMainWindow窗口中,提供了鼠标和键盘的处理函数,你需要用到时,进行重载即可。事件重载方法里的e代表了事件对象,mouseMoveEvent(self,e)里e表示QMouseEvent的对象,用对象的x()和y()方法,可以得到鼠标的x和y坐标点。更多可重载的事件方法,可以查看QWidget的源代码。除了之前讲过的重载contextMenuEvent(self, e)方法,实现上下文菜单外,常用的方法还有如下几个:
方法 |
描述 |
paintEvent(self, e) |
鼠标拖动窗口,改变窗口大小时触发; |
mouseMoveEvent(self, e) |
鼠标在窗口中移动时,触发事件; |
keyPressEvent(self, e) |
键盘按键按下后触发; |
closeEvent(self, e) |
监听关闭窗口。 |
程序清单:win_event.py
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QMessageBox,
QDesktopWidget
from PyQt5.QtCore import Qt
# 继承QWidget
class WinEvent(QWidget):
def __init__(self):
super().__init__(