I'm currently using PyQt4 and qrcode4.0.4.
from PyQt4 import QtGui, QtCore
from PIL.ImageQt import ImageQt
import qrcode
class QRLabel(QtGui.QLabel):
def __init__(self, text=""):
super(QRLabel, self).__init__()
self.setCode(text)
def setCode(self, text=""):
self.text = text
qrImg = qrcode.make(text)
imgQt = ImageQt(qrImg.convert("RGB")) # keep a reference!
pixm = QtGui.QPixmap.fromImage(imgQt)
self.setPixmap(pixm.scaled(self.size(),QtCore.Qt.KeepAspectRatio))
As you can see, there are several hurdles to be passed before you get the image on your screen. The QR code starts as a RGBA PIL Image, it is converted to RGB, then to PIL ImageQt object, then to a QPixmap, which is then placed on a QLabel with a scaling fix.
If you don't explicitly store the imgQt reference, you get rubbish when you load the widget.
My question: is there anything I could do to improve this, as it seems there are so many conversions involved.
From the qrcode docs, it appears you can create your own
image_factory
, which might allow you to streamline the process.You just need to subclass
qrcode.image.base.BaseImage
and reimplement thenew_image
,drawrect
andsave
methods. This subclass could wrap a QImage and therefore eliminate the need for the PIL conversion step.UPDATE:
Here's a demo that eliminates the PIL dependency (which is just as well, because I found PIL crashes with certain inputs):