我试图在pyqtgraph / PyQt5中的ImageView中设置比例尺,但是当我为比例尺设置setParentItem时,它将不接受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_()
答案 0 :(得分:0)
我建议您在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()
获取该对象的viewbox。
您的代码中的另一个错误是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_())