my_chart_view.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #!/usr/bin/env python
  2. # -*- encoding: utf-8 -*-
  3. '''
  4. @文件 :my_chart_view.py
  5. @时间 :2022/03/14 12:31:02
  6. @作者 :None
  7. @版本 :1.0
  8. @说明 : 重写QChartView 方法,增加缩放功能
  9. '''
  10. from math import pow
  11. from utils. qt import Qt, QChartView, QPoint, QPointF
  12. class MyChartView(QChartView):
  13. m_bMiddleButtonPressed = 0
  14. m_oPrePos = QPoint()
  15. def __init__(self, parent=None):
  16. super(MyChartView, self).__init__(parent)
  17. def mouseMoveEvent(self, event):
  18. if self.m_bMiddleButtonPressed:
  19. oDeltaPos = event.pos() - self.m_oPrePos
  20. self.chart().scroll(-oDeltaPos.x(), 0)
  21. self.m_oPrePos = event.pos()
  22. super(MyChartView, self).mouseMoveEvent(event)
  23. def mousePressEvent(self, event):
  24. if event.button() == Qt.MiddleButton:
  25. self.m_bMiddleButtonPressed = True
  26. self.m_oPrePos = event.pos()
  27. self.setCursor(Qt.OpenHandCursor)
  28. super(MyChartView, self).mousePressEvent(event)
  29. def mouseReleaseEvent(self, event):
  30. if event.button() == Qt.MiddleButton:
  31. self.m_bMiddleButtonPressed = False
  32. self.setCursor(Qt.ArrowCursor)
  33. super(MyChartView, self).mouseReleaseEvent(event)
  34. def wheelEvent(self, event):
  35. # 设置比例
  36. rVal = pow(0.999, event.delta())
  37. # 1. 读取视图基本信息
  38. oPlotAreaRect = self.chart().plotArea()
  39. oCenterPoint = oPlotAreaRect.center()
  40. # 2. 水平调整
  41. oPlotAreaRect.setWidth(oPlotAreaRect.width() * rVal)
  42. # 3. 竖直调整
  43. oPlotAreaRect.setHeight(oPlotAreaRect.height() * rVal)
  44. # 4.1 计算视点,视点不变,围绕中心缩放
  45. # QPointF oNewCenterPoint(oCenterPoint);
  46. # 4.2 计算视点,让鼠标点击的位置移动到窗口中心
  47. # QPointF oNewCenterPoint(pEvent->pos());
  48. # 4.3 计算视点,让鼠标点击的位置尽量保持不动(等比换算,存在一点误差)
  49. oNewCenterPoint = QPointF(2 * oCenterPoint - event.pos() - (oCenterPoint - event.pos()) / rVal)
  50. # 5. 设置视点
  51. oPlotAreaRect.moveCenter(oNewCenterPoint)
  52. # 6. 提交缩放调整
  53. self.chart().zoomIn(oPlotAreaRect)
  54. super(MyChartView, self).wheelEvent(event)