找回密码
 立即注册

QQ登录

只需一步,快速开始

pyqt QGraphicsView 以鼠标为中心举行缩放功能实现

2024-11-4 22:15| 发布者: 2ae29| 查看: 141| 评论: 0

摘要: 留意几个关键点: 1. 初始化 [code]class CustomGraphicsView(QGraphicsView): def __init__(self, parent=None): super(CustomGraphicsView, self).__init__(parent) self.scene = QGraphicsSc

留意几个关键点:

1. 初始化

[code]class CustomGraphicsView(QGraphicsView): def __init__(self, parent=None): super(CustomGraphicsView, self).__init__(parent) self.scene = QGraphicsScene() self.setScene(self.scene) self.setGeometry(0, 0, 1024, 600) # 以下初始化代码较为紧张 self.setMouseTracking(True) self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) # 按需开启 # self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) # 按需开启 self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse) self.setResizeAnchor(QGraphicsView.AnchorUnderMouse)[/code]

2. 关键实现函数:重界说滚轮缩放事件(可能会达不到预期效果,请看步骤3或确认初始化)

[code]def wheelEvent(self, event: QWheelEvent) -> None: if event.modifiers() == Qt.ControlModifier: mouse_pos = event.pos() scene_pos = self.mapToScene(mouse_pos) #缩放前鼠标在scene的位置 s = 1.2 #按需调解 if(event.angleDelta().y() > 0): self.scale(s,s) else: self.scale(1/s,1/s) view_point = self.mapFromScene(scene_pos) #缩放后原scene举行映射新鼠标位置 self.verticalScrollBar().setValue(int(view_point.y()-mouse_pos.y())) #通过滚动条举行移动视图 self.horizontalScrollBar().setValue(int(view_point.x()-mouse_pos.x())) return else: return super().wheelEvent(event) # 包管滚动条能滚动[/code]

3. 如果未到达预期效果,可能还需重写全部鼠标事件:

[code]def mousePressEvent(self, event: QMouseEvent) -> None: if event.button() == Qt.LeftButton: self.dragStartPos = event.pos() #用于鼠标拖拽视图 return[/code] [code]def mouseReleaseEvent(self, event: QMouseEvent) -> None: pass return[/code] [code]def mouseMoveEvent(self, event): if event.buttons() and Qt.LeftButton: # 实现鼠标拖拽视图 newpos = event.pos() delta = newpos - self.dragStartPos self.dragStartPos = newpos self.verticalScrollBar().setValue(self.verticalScrollBar().value() - delta.y()) self.horizontalScrollBar().setValue(self.horizontalScrollBar().value() - delta.x()) return[/code]

仅此记载,未重界说鼠标全部事件导致了近半个月的苦恼,固然修复了但是仍不知道什么原因

到此这篇关于pyqt QGraphicsView 以鼠标为中心举行缩放的文章就介绍到这了,更多相关pyqt QGraphicsView 鼠标缩放内容请搜刮脚本之家从前的文章或继续欣赏下面的相关文章希望大家以后多多支持脚本之家!


来源:https://www.jb51.net/python/328395i82.htm
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

最新评论

关闭

站长推荐上一条 /6 下一条

QQ|手机版|小黑屋|梦想之都-俊月星空 ( 粤ICP备18056059号 )|网站地图

GMT+8, 2025-7-1 18:52 , Processed in 0.036530 second(s), 20 queries .

Powered by Mxzdjyxk! X3.5

© 2001-2025 Discuz! Team.

返回顶部