如何在 Python 3 中腌制 QPixmap 对象字典 [英] How to pickle QPixmap object dict in Python 3
本文介绍了如何在 Python 3 中腌制 QPixmap 对象字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在 Python 3 中腌制 QPixmap 对象字典
I want to pickle QPixmap object dict in Python 3
例如
ImageQpixmapDict = {}
ImageQpixmapDict['XXX'] = QPixmap()
在这种情况下,我想腌制 ImageQpixmapDict 变量
In this situation, I want to pickle ImageQpixmapDict variable
喜欢
pickle.dump(ImageQpixmapDict, 'filePath')
我尝试使用 QSettings 来pickle QPixmap 对象,但它不起作用.
I tried to pickle QPixmap object by using QSettings, but it doesn't work.
但如你所知,QPixmap 对象不能被pickle.那么,我该如何解决这个问题.
But as you know, QPixmap object couldn't be pickled. So, How can I solve this problem.
推荐答案
只有部分 Qt 类是可选的(参见 the docs),其中没有 QPixmap,因此解决方案是创建一个实现该逻辑的派生类:
Only some Qt classes are pickable (see the docs) and among them there is no QPixmap so a solution is to create a derived class that implements that logic:
import pickle
from PyQt5 import QtCore, QtGui
class Pickable_QPixmap(QtGui.QPixmap):
def __reduce__(self):
return type(self), (), self.__getstate__()
def __getstate__(self):
ba = QtCore.QByteArray()
stream = QtCore.QDataStream(ba, QtCore.QIODevice.WriteOnly)
stream << self
return ba
def __setstate__(self, ba):
stream = QtCore.QDataStream(ba, QtCore.QIODevice.ReadOnly)
stream >> self
if __name__ == "__main__":
import sys
app = QtGui.QGuiApplication(sys.argv)
# create QPixmap
pixmap = QtGui.QPixmap(100, 100)
pixmap.fill(QtGui.QColor("red"))
with open("data.pickle", "wb") as f:
image_dict = dict()
image_dict["XXX"] = Pickable_QPixmap(
pixmap
) # convert QPixmap to Pickable_QPixmap
pickle.dump(image_dict, f)
with open("data.pickle", "rb") as f:
image_dict = pickle.load(f)
pixmap = image_dict["XXX"]
qpixmap = QtGui.QPixmap(pixmap) # convert Pickable_QPixmap to QPixmap
assert qpixmap.size() == pixmap.size() == QtCore.QSize(100, 100)
assert qpixmap.toImage() == pixmap.toImage()
这篇关于如何在 Python 3 中腌制 QPixmap 对象字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文