Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
417 views
in Technique[技术] by (71.8m points)

python - Bug when drawing a QImage on a widget with PIL and PyQt

I'm trying to write a small graphic application, and I need to construct some image using PIL that I show in a widget. The image is correctly constructed (I can check with im.show()), I can convert it to a QImage, that I can save normally to disk (using QImage.save), but if I try to draw it directly on my QWidget, it only show a white square.

Here I commented out the code that is not working (converting the Image into QImage then QPixmap result in a white square), and I made a dirty hack to save the image to a temporary file and load it directly in a QPixmap, which work but is not what I want to do

https://gist.github.com/f6d479f286ad75bf72b7

Someone has an idea?

If it can help, when I try to save my QImage in a BMP file, I can access its content, but if I try to save it to a PNG it is completely white

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Had the same problem, then noticed, that ImageQt objects are not QImages, but can simply be casted to those

#!/usr/bin/python
# -*- coding: utf-8 -*-
#written by Sebastian Stetter in 2010


import sys
from PIL import Image
from PIL.ImageQt import ImageQt

from PyQt4.QtGui import *
from PyQt4.QtCore import *



def PILimageToQImage(pilimage):
    """converts a PIL image to QImage"""
    imageq = ImageQt(pilimage) #convert PIL image to a PIL.ImageQt object
    qimage = QImage(imageq) #cast PIL.ImageQt object to QImage object -that′s the trick!!!
    return qimage




if __name__ == "__main__":
    #Testcode
    app = QApplication(sys.argv)

    pim = Image.open(unicode(QFileDialog().getOpenFileName()))
    pim.show() #show pil image

    qim = PILimageToQImage(pim)
    pm = QPixmap(qim)
    lbl = QLabel()
    lbl.setPixmap(pm)
    lbl.show() #show label with qim image

    sys.exit(app.exec_())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...