赞
踩
鼠标GUI程序中另外一种重要的交互方式,Qt中的鼠标事件包括鼠标点击、松开鼠标按键,移动鼠标到指定区域或者离开特定区域,更改鼠标指针的形状等等。
对鼠标最常见的操作就是点击和释放,进行点击释放操作,将调用以下方法:
必须注意在双击之前的其他事件。双击时的事件顺序为:mouseButtonPress --> mouseButtonRelease --> mouseButtonDblClick --> mouseButtonPress --> mouseButtonRelease。
QApplicaption类的setDoubleClickInterval()方法可设置双击的时间间隔;doubleClickInterval( )方法返回双击的时间间隔。
event参数是QMouseEvent对象,存储事件的其他信息。常用方法有:
如果要让父控件继续收到鼠标事件,要调用事件的ignore()方法;否则,调用accept()。如果一个控件的Qt.WA_NoMousePropagation的属性设为True,则不会将事件传递给父控件。调用setAttribute( )方法可修改此参数:
button.setAttribute (Qt.WA_NoMousePropagation, True)
缺省情况下,鼠标事件只拦截控件区域中的鼠标操作。如果可拦截控件区域以外的鼠标事件,必须调用grabMouse()方法;释放时,调用releaseMouse()。
重载mouseMoveEvent(self, event), 可以处理鼠标指针的移动。在缺省情况下,只有按下鼠标键并移动时,才会调用mouseMoveEvent()。 如果要处理一般情况下的鼠标移动(比如未按下鼠标键), 需要调用setMouseTracking(True)。如果要处理窗口中鼠标移动的事件,需要调用grabMouse()。
event对象中的pos()函数返回值为相对于控件的坐标,如果要转换成相对于父控件或者屏幕坐标,需要调用QWidget类的以下方法:
鼠标指针移进和移出控件时,下列方法将被调用:
参数event为QEvent对象。
鼠标滚轮操作事件由wheelEvent(self, event)方法来处理。参数event是一个QWheelEvent对象,它包含滚轮操作的相关信息。有以下常用方法可使用:
- angle=event.angleDelta( ) /8
- angleX=angle.x()
- angleY=angle.y()
如果要让父控件继续收到滚轮事件,要调用事件的ignore()方法;否则,调用accept()。
QWidget类中以下方法设置和管理鼠标指针:
等常用鼠标形状。
使用QApplication类中的以下静态方法来控制整个应用程序的鼠标形状:
setOverrideCursor()和restoreOverrideCursor( )通常配合使用。
测试程序中,使用鼠标演示了在窗口中绘制连续线,完整代码如下:
- import sys
- from PyQt5 import QtCore, QtGui, QtWidgets
- from PyQt5.QtCore import Qt, QEvent, QPoint
- from PyQt5.QtGui import QPainter, QPen, QPixmap
- from PyQt5.QtWidgets import QApplication, QWidget
-
- class DemoMouseEvent(QWidget):
- def __init__(self, parent=None):
- super(DemoMouseEvent, self).__init__(parent)
-
- # 设置窗口标题
- self.setWindowTitle('实战PyQt5: 鼠标事件演示')
- # 设置窗口大小
- self.setFixedSize(480, 320)
-
- self.beginPoint = QPoint() #起始点
- self.endPoint = QPoint() #结束点
-
- self.pixmap = QPixmap(self.rect().size())
- self.pixmap.fill(Qt.lightGray)
-
- #重绘窗口事件
- def paintEvent(self, event):
- pp = QPainter(self.pixmap)
- pp.setPen(QPen(Qt.blue, 2)) #设置画笔
-
- #绘制直线
- pp.drawLine(self.beginPoint, self.endPoint)
- #上一直线的终点就是下一直线的起点
- self.beginPoint = self.endPoint
-
- #在画布上画出
- painter = QPainter(self)
- painter.drawPixmap(0, 0, self.pixmap)
-
- def mousePressEvent(self, event):
- #鼠标左键按下
- if event.button() == Qt.LeftButton:
- self.startPoint = event.pos()
-
- def mouseReleaseEvent(self, event):
- #鼠标左键释放
- if event.button() == Qt.LeftButton:
- self.endPoint = event.pos()
- #重新绘制
- self.update()
-
- def mouseMoveEvent(self, event):
- #鼠标左键按下的同时移动鼠标
- if event.buttons() and Qt.LeftButton:
- self.endPoint = event.pos()
- #重新绘制
- self.update()
-
- if __name__ == '__main__':
- app = QApplication(sys.argv)
- window = DemoMouseEvent()
- window.show()
- sys.exit(app.exec())
运行结果如下图:
测试鼠标事件
前一篇: 实战PyQt5: 097-键盘事件
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。