from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * class GraphicsView(QGraphicsView): def init(self, parent=None): super(GraphicsView, self).init(parent) self.setDragMode(QGraphicsView.RubberBandDrag) def mousePressEvent(self, event): if event.button() == Qt.LeftButton: self.origin = event.pos() self.rubberBand = QRubberBand(QRubberBand.Rectangle, self) self.rubberBand.setGeometry(QRect(self.origin, QSize())) self.rubberBand.setStyleSheet("background-color: rgba(255, 0, 0, 50);") self.rubberBand.show() super(GraphicsView, self).mousePressEvent(event) def mouseMoveEvent(self, event): if self.rubberBand.isVisible(): self.rubberBand.setGeometry(QRect(self.origin, event.pos()).normalized()) super(GraphicsView, self).mouseMoveEvent(event) def mouseReleaseEvent(self, event): if event.button() == Qt.LeftButton: self.rubberBand.hide() rect = self.viewport().rect().intersected(self.rubberBand.geometry()) rect_mapped = self.mapToScene(rect).boundingRect() print(rect_mapped) super(GraphicsView, self).mouseReleaseEvent(event) class MainWindow(QMainWindow): def init(self): super().init() self.graphics_view = GraphicsView(self) self.scene = QGraphicsScene(self.graphics_view) self.graphics_view.setScene(self.scene) self.image = QImage("E:/123.bmp") self.pixmap = QPixmap.fromImage(self.image) self.scene.addPixmap(self.pixmap) self.setCentralWidget(self.graphics_view) if name == 'main': import sys app = QApplication(sys.argv) window = MainWindow() window.setGeometry(500, 200, 800, 600) window.show() sys.exit(app.exec_()) 在这个代码上,增加滑动滚轮可根据鼠标位置进行放大缩小
时间: 2024-02-23 14:01:25 浏览: 148
PyQt5.QtWebEngine + JS 实现网页与Python的数据通信
5星 · 资源好评率100%
你可以在 GraphicsView 类中重新实现 wheelEvent() 方法,来处理鼠标滚轮事件,并根据鼠标位置进行放大缩小。以下是代码示例:
```python
class GraphicsView(QGraphicsView):
def __init__(self, parent=None):
super(GraphicsView, self).__init__(parent)
self.setDragMode(QGraphicsView.RubberBandDrag)
self.setRenderHint(QPainter.Antialiasing)
def wheelEvent(self, event):
# 获取当前鼠标位置
mouse_pos = event.pos()
# 获取当前视图的中心点
view_center = self.viewport().rect().center()
# 将鼠标位置转换为场景坐标系下的位置
scene_pos = self.mapToScene(mouse_pos)
# 计算缩放因子
zoom_factor = 1.2 if event.angleDelta().y() > 0 else 1 / 1.2
# 缩放视图
self.scale(zoom_factor, zoom_factor)
# 将视图中心点移动到鼠标位置
view_center_after = self.mapFromScene(scene_pos).toPoint()
delta = view_center_after - mouse_pos
self.horizontalScrollBar().setValue(self.horizontalScrollBar().value() - delta.x())
self.verticalScrollBar().setValue(self.verticalScrollBar().value() - delta.y())
```
在这个示例中,我们首先获取当前鼠标的位置,然后获取当前视图的中心点。接着将鼠标位置转换为场景坐标系下的位置,然后计算缩放因子。在缩放视图之后,我们将视图中心点移动到鼠标位置上,以达到缩放的效果。
阅读全文