【问题标题】:ScaleBar in pyqtgraph won't setParentItempyqtgraph中的ScaleBar不会设置ParentItem
【发布时间】:2019-06-15 11:02:50
【问题描述】:

我试图在 pyqtgraph / PyQt5 的 ImageView 中设置比例尺,但是当我为比例尺设置ParentItem 时,它不会接受 ImageView、ImageItem 或 ViewBox。没有错误信息但是整个程序崩溃了。

from PyQt5 import QtGui
import pyqtgraph as pg
import numpy as np

app = QtGui.QApplication([])

imvOCTTopLeft = pg.ImageView(view=pg.PlotItem())
imvOCTTopLeft.setImage(np.random.normal(size=(100,100)))
scale = pg.ScaleBar(size=0.1)
im=imvOCTTopLeft.getImageItem()
scale.setParentItem(im)

imvOCTTopLeft.show()

app.exec_()

【问题讨论】:

    标签: python pyqt pyqt5 pyqtgraph


    【解决方案1】:

    我建议您在 CMD 或终端中执行您的代码,以便获得有关错误的更多信息,如果您这样做,您将收到以下消息:

    Traceback (most recent call last):
      File "/usr/lib/python3.7/site-packages/pyqtgraph/graphicsItems/GraphicsObject.py", line 23, in itemChange
        self.parentChanged()
      File "/usr/lib/python3.7/site-packages/pyqtgraph/graphicsItems/ScaleBar.py", line 44, in parentChanged
        view.sigRangeChanged.connect(self.updateBar)
    AttributeError: 'ImageItem' object has no attribute 'sigRangeChanged'
    Aborted (core dumped)
    

    导致该错误是因为setParentItem() 方法需要一个 ViewBox,因为它具有 sigRangeChanged 信号,如果有某种类型的缩放,它允许更新 ScaleBar。然后,您可以通过 view 属性获取 ViewBox,但如果您使用视图在构造函数中传递参数(pg.ImageView(view = pg.PlotItem())),那么您必须使用 getViewBox() 获取该对象的视图框。

    您代码中的另一个错误是 QApplication 属于 PyQt5 的 QtWidgets 子模块。

    from PyQt5 import QtWidgets
    import pyqtgraph as pg
    import numpy as np
    
    if __name__ == '__main__':
        import sys
    
        app = QtWidgets.QApplication(sys.argv)
    
        imvOCTTopLeft = pg.ImageView(view=pg.PlotItem())
        imvOCTTopLeft.setImage(np.random.normal(size=(100,100)))
        scale = pg.ScaleBar(size=10)
        viewbox = imvOCTTopLeft.view
        if not isinstance(viewbox, pg.ViewBox): viewbox = viewbox.getViewBox()
        scale.setParentItem(viewbox)
        scale.anchor((1, 1), (1, 1), offset=(-200, -20))
        imvOCTTopLeft.show()
    
        sys.exit(app.exec_())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-30
      • 2014-05-17
      • 2018-10-05
      • 2019-05-06
      • 2017-04-26
      • 2016-01-05
      • 2020-01-30
      • 2019-05-17
      相关资源
      最近更新 更多