PySide6 Convert ImageQt to QPixmap

Viewed 702

I'm converting old Python 2.7 code to Python 3 and get following error on the last line:

ar = imgArray*255
ar = numpy.clip(ar, 0, 255, out=ar)
img = Image.fromarray(ar.astype("uint8"))
qim = ImageQt.ImageQt(img)   
pm = QtGui.QPixmap.fromImage(qim)


TypeError: 'PySide6.QtGui.QPixmap.fromImage' called with wrong argument types:
  PySide6.QtGui.QPixmap.fromImage(ImageQt)

So, the question is: how to get QPixmap from ImageQt object in PySide6?

1 Answers

Pil.ImageQt decides the backend based on whether the library was imported, if it did, then it will use that otherwise there is an internal order (PyQt6, PySide6, PyQt5, PySide2 at this time). So to avoid these problems you have to first import PySide6 and then PIL.

import PySide6
from PySide6 import QtCore, QtGui

import PIL
from PIL import Image, ImageQt

import numpy as np

print(
    f"Tested with:\n- PIL version: {PIL.__version__},\n- PySide6 version: {PySide6.__version__},\n- Qt Version: {QtCore.qVersion()}\n- Numpy version: {np.__version__}"
)

app = QtGui.QGuiApplication()

ar = np.random.randint(255, size=(900, 800, 3), dtype=np.uint8)
img = Image.fromarray(ar.astype(np.uint8))
qim = ImageQt.ImageQt(img)
pm = QtGui.QPixmap.fromImage(qim)
assert not pm.isNull()

Output:

Tested with:
- PIL version: 8.3.1,
- PySide6 version: 6.1.2,
- Qt Version: 6.1.2
- Numpy version: 1.21.2
Related