0

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?

Renato Gama
  • 16,431
  • 12
  • 58
  • 92

2 Answers2

0

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

Martin Beckett
  • 94,801
  • 28
  • 188
  • 263
0

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.

Gary Hughes
  • 4,400
  • 1
  • 26
  • 40
  • Totally works. Actually a work around I found was to load the file using a QIMage first: `qimg = QImage("test.pgm") pixmap = QPixmap.fromImage(qimg) self.scene.addPixmap(pixmap)`. But your method is even simpler. Thank you. – itISiBOWMAN Jul 25 '12 at 20:48