How do I display a PGM file within a QGraphicsView?

1.3k Views Asked by At

I am trying to display a PGM file using the following test application. The code works with a PNG file, but not PGM:

import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import Image
import ImageQt

class MyView(QGraphicsView):
    def __init__(self):
        QGraphicsView.__init__(self)

        self.scene = QGraphicsScene(self)
        self.setScene(self.scene)

        img = Image.open('test.pgm') # works with 'test.png' 
        self.imgQ = ImageQt.ImageQt(img)
        pixmap = QPixmap.fromImage(self.imgQ)
        self.scene.addPixmap(pixmap)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    view = MyView()
    view.show()
    sys.exit(app.exec_())

How can I display a PGM file within the QGraphicsView?

2

There are 2 best solutions below

1
On

It looks like you're using PIL to open the image, convert to a QImage and then convert that to a QPixmap.

Is there any reason why you can't just load the PGM directly into a QPixmap and avoid PIL?

Replacing

img = Image.open('test.pgm') # works with 'test.png' 
self.imgQ = ImageQt.ImageQt(img)
pixmap = QPixmap.fromImage(self.imgQ)
self.scene.addPixmap(pixmap)

with

pixmap = QPixmap('test.pgm')
self.scene.addPixmap(pixmap)

should work for you.

1
On

QImage supports reading PGM files. Have you checked that img is loaded correctly?

Perhaps you have abad file, or a typo in the name, or wrong permissions