Search code examples
python-3.ximageviewqt-designerpyqtgraph

Convert pg.ImageItem to pg.ImageView to show image and z-axis slider


I am having a problem with pyqtgraph and my lack of understanding I think. I have some code (see below) which works for embedding a "ImageItem" inside a pyqt designer window. I wish however to use "ImageView" so that I can use some of the other features (e.g. z-axis slider). How can I do this? When I change the command to "ImageView" I get the following error

AttributeError: 'ImageView' object has no attribute 'zValue'

Can anyone tell me where I am going wrong please. Thanks for any help on this.

from PyQt5 import uic, QtCore, QtGui, QtWidgets
import sys

import pyqtgraph as pg
import numpy as np

class ViewData(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(ViewData, self).__init__(parent)
        uic.loadUi('test.ui',self)

        win = pg.GraphicsLayout()
        p = win.addViewBox()

        imv = pg.ImageItem()
        self.view.setCentralItem(win)
        self.view.show()

        imagedata = np.random.random((256,256))
        imv.setImage(imagedata)
        p.addItem(imv)

def main():
    app = QtWidgets.QApplication(sys.argv)      # A new instance of QApplication
    vd = ViewData()                             # We set the form to be our MainWindow (design)
    vd.show()                                   # Show the form
    app.exec_()                                 # and execute the app

if __name__ == '__main__':                      # if we're running file directly and not importing it
    main()                                      # run the main function

Solution

  • This is how you would add an ImageView to a QtWidget.

    from PyQt4 import QtGui
    import sys
    
    import pyqtgraph as pg
    import numpy as np
    
    class ViewData(QtGui.QMainWindow):
        def __init__(self, parent=None):
            super(ViewData, self).__init__(parent)
            self.widget = QtGui.QWidget()
            self.widget.setLayout(QtGui.QHBoxLayout())
    
            imv = pg.ImageView()
            imagedata = np.random.rand(256,256)
            imv.setImage(imagedata)
    
            self.widget.layout().addWidget(imv)
            self.setCentralWidget(self.widget)
            self.show()
    
    
    def main():
        app = QtGui.QApplication(sys.argv)      
        vd = ViewData()               
        vd.show()                      
        app.exec_()                  
    
    if __name__ == '__main__':
        main()     
    

    It's in PyQt4, but that can easily be changed.