参考连接:https://www.cnblogs.com/zhuluqing/p/9028816.htmlhtml
pyqt中,每一个事件类型都被封装成相应的事件类,如鼠标事件为QMouseEvent,键盘事件为QKeyEvent等。而它们的基类是QEvent。python
accept() 表示事件已处理,不须要向父窗口传播ide
ignore()表示事件未处理,继续向父窗口传播f函数
type()返回事件类型,如QtCore.QEvent.MouseButtonPress,通常由基事件调用。由于其它事件已经知道本身的事件类型了。spa
还有一个自定义事件的注册方法。指针
buttons()返回哪一个鼠标按键被按住了。如Qt.LeftButtonrest
globalPos()返回鼠标相对屏幕的位置QPointcode
pos()返回鼠标相对处理事件的窗口的位置htm
mousePressEvent(QMouseEvent)对象
mouseReleaseEvent(event)
mouseMoveEvent(event)
# 事件。 """重写鼠标事件,实现窗口拖动。""" def mousePressEvent(self, event): if event.buttons() == Qt.LeftButton: self.setCursor(Qt.OpenHandCursor) self.parent.m_drag = True self.parent.m_DragPosition = event.globalPos()-self.parent.pos() event.accept() def mouseMoveEvent(self, event): try: if event.buttons() and Qt.LeftButton: self.parent.move(event.globalPos()-self.parent.m_DragPosition)#move将窗口移动到指定位置 event.accept() except AttributeError: pass def mouseReleaseEvent(self, event): if event.button()==Qt.LeftButton: self.m_drag = False self.unsetCursor()
处理鼠标事件的频率不低于键盘事件。包括按下、松开鼠标按键;移动鼠标到特定区域或离开特定区域;更改鼠标指针的形状,等等。
1.按下、松开鼠标按键
按下并释放鼠标按钮时,将调用如下方法:
event参数是QMouseEvent对象,存储事件的其余信息。有如下方法:
若是要让父控件继续收到鼠标事件,要调用事件的ignore()方法;不然,调用accept()。
若是一个控件的QtCore.Qt.WA_NoMousePropagation的属性设为True,则不会将事件传递给父控件。调用setAttribute( )方法可修改此参数:
button.setAttribute (QtCore.Qt.WA_NoMousePropagation, True)
缺省状况下,鼠标事件只拦截控件区域上的鼠标操做。若是可拦截控件区域如下的鼠标事件,必须调用grabMouse( )方法;释放时,调用releaseMouse( )。
2.鼠标指针
要处理鼠标指针的移动,须要重载mouseMoveEvent(self,event)方法。缺省状况下,只有按下鼠标键移动时,才会调用mouseMoveEvent( )。若是要处理包括普通的移动,须要以参数为True调用setMouseTracking() 方法。若是要处理窗口中鼠标移动的事件,须要调用grabMouse( )方法。
event对象的pos( )返回值为相对控件的坐标,要转换成相对父控件或屏幕的坐标,须要调用QWidget类的如下方法:
3. 鼠标移进和移出控件 鼠标移进和移出控件时,下列方法将被调用:
event是一个QEvent对象,并不包括附加信息。
4.滚动鼠标
wheelEvent (self, event)方法可用来处理鼠标滚动事件。event是一个QWheelEvent对象,包含滚轮操做的相关信息。有如下方法可调用:
若是要让父控件继续收到滚轮事件,要调用事件的ignore()方法;不然,调用accept()。
5.更改鼠标指针形状
要修改鼠标进入控件后的形状,可调用QWidget的下列方法:
setCursor(QCursor qcr) - 参数qcr为QCursor对象或 Qtcore.Qt 类的枚举值,如:ArrowCursor(标准箭头)、upArrowCursor(向上箭头)、 CrossCursor(十字光标)、Waitcursor (沙漏),等等。
setCursor(QtCore.Qt.WaitCursor)
使用QApplication类中的如下静态方法来控制整个应用程序的鼠标形状:
setOverrideCursor()和restoreOverrideCursor( )一般配合使用。