python - pyqtgraph自定义缩放问题

标签 python python-3.x pyqt4 pyqtgraph

我使用 pyqtgraph 库进行绘图。我真的很喜欢绘图上的鼠标交互(缩放、平移……)。

对于我的一些绘图,我想在滚动鼠标滚轮时更改缩放行为。标准实现是同时在 x 和 y 方向上缩放。在 x 方向上缩放在这些图上没有意义,所以我想禁用它。我尝试了以下方法:

###################################################################
#                                                                 #
#                     PLOTTING A LIVE GRAPH                       #
#                  ----------------------------                   #
#                                                                 #
###################################################################

import sys
import os
from PyQt4 import QtGui
from PyQt4 import QtCore
import pyqtgraph as pg
import numpy as np

# Override the pg.ViewBox class to add custom
# implementations to the wheelEvent
class CustomViewBox(pg.ViewBox):
    def __init__(self, *args, **kwds):
        pg.ViewBox.__init__(self, *args, **kwds)
        #self.setMouseMode(self.RectMode)


    def wheelEvent(self, ev, axis=None):
        # 1. Pass on the wheelevent to the superclass, such
        #    that the standard zoomoperation can be executed.
        pg.ViewBox.wheelEvent(ev,axis)

        # 2. Reset the x-axis to its original limits
        #
        # [code not yet written]
        #

class CustomMainWindow(QtGui.QMainWindow):

    def __init__(self):

        super(CustomMainWindow, self).__init__()

        # 1. Define look and feel of this window
        self.setGeometry(300, 300, 800, 400)
        self.setWindowTitle("pyqtgraph example")

        self.FRAME_A = QtGui.QFrame(self)
        self.FRAME_A.setStyleSheet("QWidget { background-color: %s }" % QtGui.QColor(210,210,235,255).name())
        self.LAYOUT_A = QtGui.QHBoxLayout()
        self.FRAME_A.setLayout(self.LAYOUT_A)
        self.setCentralWidget(self.FRAME_A)

        # 2. Create the PlotWidget(QGraphicsView)
        # ----------------------------------------
        self.vb = CustomViewBox()
        self.plotWidget = pg.PlotWidget(viewBox=self.vb, name='myPlotWidget')
        self.LAYOUT_A.addWidget(self.plotWidget)
        self.plotWidget.setLabel('left', 'Value', units='V')
        self.plotWidget.setLabel('bottom', 'Time', units='s')
        self.plotWidget.setXRange(0, 10)
        self.plotWidget.setYRange(0, 100)

        # 3. Get the PlotItem from the PlotWidget
        # ----------------------------------------
        self.plotItem = self.plotWidget.getPlotItem()

        # 4. Get the PlotDataItem from the PlotItem
        # ------------------------------------------
        # The plot() function adds a new plot and returns it.
        # The function can be called on self.plotWidget or self.plotItem
        self.plotDataItem = self.plotItem.plot()
        self.plotDataItem.setPen((255, 240, 240))
        self.plotDataItem.setShadowPen(pg.mkPen((70, 70, 30), width=2, cosmetic=True))


        # 5. Create the x and y arrays
        # -----------------------------
        n = np.linspace(0, 499, 500)
        self.y = 50 + 5 * (np.sin(n / 8.3)) + 7 * (np.sin(n / 7.5)) - 5 * (np.sin(n / 1.5))
        self.x = 10 * n / len(n)
        self.plotDataItem.setData(x=self.x, y=self.y)

        self.show()


if __name__== '__main__':
    app = QtGui.QApplication(sys.argv)
    QtGui.QApplication.setStyle(QtGui.QStyleFactory.create('Plastique'))
    myGUI = CustomMainWindow()


    sys.exit(app.exec_())

只需将这段代码复制粘贴到一个新的 Python 文件中,您应该会得到以下输出:

enter image description here

不幸的是,每次 mouseWheel 事件都会弹出一条错误消息:

Traceback (most recent call last):
  File "pyTest.py", line 26, in wheelEvent
    pg.ViewBox.wheelEvent(ev,axis)
  File "C:\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\ViewBox\ViewBox.py", line 1206, in wheelEvent
    mask = np.array(self.state['mouseEnabled'], dtype=np.float)
AttributeError: 'QGraphicsSceneWheelEvent' object has no attribute 'state'

我的系统如下:

  • Python 版本:3.5.2
  • PyQt 版本:4.11.4
  • Qt版本:4.8.7
  • pyqtgraph版本:0.9.10

最佳答案

我的同事指出我必须在覆盖 wheelEvent 函数时添加 self 作为第一个参数:

# Override the pg.ViewBox class to add custom
# implementations to the wheelEvent
class CustomViewBox(pg.ViewBox):
    def __init__(self, *args, **kwds):
        pg.ViewBox.__init__(self, *args, **kwds)
        #self.setMouseMode(self.RectMode)


    def wheelEvent(self, ev, axis=None):
        print(str(self.viewRange()))

        # 1. Pass on the wheelevent to the superclass, such
        #    that the standard zoomoperation can be executed.
        pg.ViewBox.wheelEvent(self,ev,axis) # <- To override the function
                                                 properly, one should add
                                                 'self' as first argument

        # 2. Reset the x-axis to its original limits
        self.setXRange(0,10)

现在可以了。但唯一的缺点是下面的代码行:

    # 2. Reset the x-axis to its original limits
    self.setXRange(0,10)

这样做会更好:

def wheelEvent(self, ev, axis=None):
    # 1. Determine initial x-range
    initialRange = self.viewRange()

    # 2. Call the superclass method for zooming in
    pg.ViewBox.wheelEvent(self,ev,axis)

    # 3. Reset the x-axis to its original limits
    self.setXRange(initialRange[0][0],initialRange[0][1])

问题在于函数 self.viewRange() 不返回 [0,10] 而是返回 [-0.37, 10.37]。 viewBox 在左侧和右侧添加了一些边距。如果你继续这样做,最终这些边距会随着时间的推移而漂移: [-0.37, 10.37] -> [-0.74, 10.74] -> ...

关于python - pyqtgraph自定义缩放问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39699702/

相关文章:

python - 如何在 get_or_create 中用另一个对象更新对象?

python - 在外部循环中更新 Tkinter GUI

python - 如果不调用 thread.stop() 或 thread.join() 方法,python 中的线程什么时候会死亡?

linux - 如何在 pyqt4 的 textEdit 中显示 os.system()

python - 如何在一个主窗口上做多个用户界面

python - 减少在 python 中从大数据库搜索的时间

python - Python 如何比较字符串和整数?

python - 在 Python 列表中高效搜索部分字符串

python - 获取 "Can' t 连接到 '203.171.xx.xx' 上的 MySQL 服务器(13)“当尝试在 cgi 中使用 python 连接到远程 sqlserver 时

Python 3.6 合并字典失败