PySide6中ImageQt转QPixmap触发类型报错,如何正确实现转换?
PySide6从ImageQt获取QPixmap报错解决方案
运行代码触发的类型错误如下:
TypeError: 'PySide6.QtGui.QPixmap.fromImage' called with wrong argument types: PySide6.QtGui.QPixmap.fromImage(ImageQt)
错误原因
PySide6的QPixmap.fromImage()仅支持接收原生PySide6.QtGui.QImage类型的参数,而PIL提供的ImageQt.ImageQt返回的是PIL封装的兼容对象,并非PySide6原生QImage类型,类型不匹配因此触发报错。
解决方案
方案1:直接从PIL Image构造原生QImage(推荐)
不需要依赖PIL的ImageQt模块,兼容性和稳定性更高,代码修改如下:
import numpy from PIL import Image from PySide6.QtGui import QImage, QPixmap ar = imgArray*255 ar = numpy.clip(ar, 0, 255, out=ar) img = Image.fromarray(ar.astype("uint8")) # 根据图片模式选择对应QImage格式 if img.mode == "RGB": format = QImage.Format_RGB888 elif img.mode == "RGBA": format = QImage.Format_RGBA8888 elif img.mode == "L": format = QImage.Format_Grayscale8 else: img = img.convert("RGB") format = QImage.Format_RGB888 qim = QImage(img.tobytes(), img.width, img.height, img.width * len(img.getbands()), format) pm = QPixmap.fromImage(qim)
方案2:兼容ImageQt用法
如果需要保留原有ImageQt的调用逻辑,确保Pillow版本≥9.1.0(已支持PySide6兼容),修改代码如下:
import numpy from PIL import Image from PIL.ImageQt import ImageQt from PySide6.QtGui import QPixmap ar = imgArray*255 ar = numpy.clip(ar, 0, 255, out=ar) img = Image.fromarray(ar.astype("uint8")) qim = ImageQt(img) # 调用copy()方法导出为PySide6原生QImage类型 pm = QPixmap.fromImage(qim.copy())
内容的提问来源于stack exchange,提问作者dmitry
相关产品推荐
相关产品推荐

