PySide6 将 ImageQt 转换为 QPixmap

PySide6 Convert ImageQt to QPixmap

我正在将旧的 Python 2.7 代码转换为 Python 3,并在最后一行出现以下错误:

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)

所以,问题是:如何从 PySide6 中的 ImageQt 对象获取 QPixmap?

Pil.ImageQt根据库是否被导入来决定后端,如果导入则使用,否则有内部顺序(此时为PyQt6、PySide6、PyQt5、PySide2)。所以为了避免这些问题,你必须先导入 PySide6,然后再导入 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()

输出:

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