
python pyqt-QGraphicsView通过改写鼠标事件实现图像的放大缩小和拖动功能记录
pyqt-QGraphicsView通过改写鼠标事件实现图像的放大缩小和拖动功能记录
·
功能描述:
1,通过鼠标滚轮实现图像的放大缩小
2,按住鼠标左键移动实现图像的拖动
代码
class GraphicsView(QGraphicsView):
#继承父类传递的参数
def __init__(self,parent=None):
super().__init__(parent)
self.factor = 1.0
self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
def wheelEvent(self, event):
self.scaleView(math.pow(2.0, -event.angleDelta().y() / 240.0))#这里是滚轮缩放倍率
def scaleView(self, scaleFactor):
self.factor = self.transform().scale(scaleFactor, scaleFactor).mapRect(QRectF(0, 0, 1, 1)).width()
if self.factor < 0.2 or self.factor > 100:
return
self.scale(scaleFactor, scaleFactor)
def mousePressEvent(self, event):#记录在按下鼠标时鼠标的坐标
self.press_point = event.pos()
def mouseMoveEvent(self, event):
dis_point = event.pos() - self.press_point#一旦鼠标移动便会记录与上次的坐标差,这个事件会在鼠标移动中不断触发
self.press_point = event.pos()
x_dis = dis_point.x()/self.factor #用图像放大的倍率做换算,使鼠标移动距离与图像移动距离尽量保持一致
y_dis = dis_point.y()/self.factor
if 0.0 < x_dis < 1.0:#每次触发事件的移动距离必须大于1,不然会有明显卡顿感
x_dis = 1.0
if -1.0 < x_dis < 0.0:
x_dis = -1.0
if 0 < y_dis < 1.0:
y_dis = 1.0
if -1.0 < y_dis < 0.0:
y_dis = -1.0
#self.sceneRect().width()/2和self.sceneRect().height()/2的作用是让图像在首次进行移动时居中
self.setSceneRect(self.sceneRect().x() - x_dis + self.sceneRect().width()/2,self.sceneRect().y() - y_dis + self.sceneRect().height()/2,1,1)#FIXME:这里可能是一个bug,但现在利用这个bug,如果不把宽和高设定为1,那么图片将无法移动
print("横:{}".format(str(self.sceneRect().x() - x_dis)) + "纵:{}".format(str(self.sceneRect().y() - y_dis)) + "宽:{}".format(str(int(self.sceneRect().width())))\
+"高:{}".format(str(int(self.sceneRect().height()))))#仅做记录
self.update()
更多推荐
所有评论(0)