PyQt imageViewer does not working properly...

Hans-Peter Jansen hpj at urpla.net
Tue Oct 5 16:22:58 EDT 2010


On Tuesday 05 October 2010, 00:29:04 Polimeno wrote:
> Hello guys,
>
> I have been looking throughout the web for some PyQt Image Viewer :
>
> http://nullege.com/codes/show/src%40pyformex-0.8.2%40pyformex%40gui%40ima
>geViewer.py/78/PyQt4.QtGui.QImage#
>
>
> Unfortunately, everytime I input any kind of image type
> (.jpeg, .tga, .png, whatver) It doesn´t show me the image inside the
> widget itself.... looks like it ignores the path I did pick...
>
> Even if I use a simple snippet like one below, I can´t get my display
> image...
>
> from PyQt4.QtGui import *
> from PyQt4.QtCore import *
> import sys
>
> class ImageViewer(QWidget):
>
>     def __init__(self, imgFile):
>         QWidget.__init__(self)
>         self.image = QImage(imgFile)
>         print self, file_Path, '\n'
>         self.update()
>
>     def paintEvent(self, event):
>         self.painter = QPainter(self)
>         self.painter.drawImage(0, 0, self.image)
>
> if __name__ == "__main__":
>     Qapp = QApplication(sys.argv)
>     Iviewer = ImageViewer(imgFile='C:\\Users\\Administrador\\Desktop\
> \Img_001.jpg')
>     Iviewer.show()
>     Qapp.exec_()
>
> What am I missing ?

Hmm, first of all, a QLabel would be better suited for the task in question, 
since that one would display some image just fine without any painter, but 
anyway, here's a working example:

import sys
from PyQt4 import QtCore, QtGui

class Widget(QtGui.QWidget):
    def __init__(self, imgFile, parent = None):
        super(Widget, self).__init__(parent)
        self.image = QtGui.QImage(imgFile)
        self.resize(self.image.size())

    def paintEvent(self, event):
        p = QtGui.QPainter(self)
        p.drawImage(event.rect(), self.image)

try:
    imgFile = sys.argv[1]
except IndexError:
    print >> sys.stderr, "%s: image" % sys.argv[0]
    sys.exit(1)
app = QtGui.QApplication(sys.argv)
iv = Widget(imgFile)
iv.show()
sys.exit(app.exec_())

Depending on the window frame size, the image might be distorted with small 
images, because the painter tries to fit the image into the window. On the 
plus side, this code is able to cope with all supported image formats, 
hence even svg files.

Hth,
Pete



More information about the Python-list mailing list