我有一个存储要生成的QPixmap的类。我想对它进行分类,这样它就可以从一个会话重用到下一个会话,而不需要从初始图像重新计算(有一些调整大小和繁重的操作)。
QPixmap是不可选择的,所以它不能工作,但我注意到QByteArray是可选择的。因此,我尝试实现一个'getstate','setstate‘解决方案。见下文。
class StoreQPixmap:
def __init__(self):
# store QPixmap computed image - It is a dictionary as several images can
be stored for the same picture and
# the dictionary key is the way to distinguish them
self._qpixmap = {}
def set_qpixmap(self, hash_, qpixmap):
self._qpixmap[hash_] = qpixmap
def get_qpixmap(self, hash_):
try:
return self._qpixmap[hash_]
except KeyError:
return None
def del_qpixmap(self, hash_):
try:
del self._qpixmap[hash_]
return True
except KeyError:
return False
def __getstate__(self):
# QPixmap is not pickable so let's transform it into QByteArray that does support pickle
state = []
qbyte_array = QByteArray()
buffer = QBuffer(qbyte_array)
for key, value in self._qpixmap.items():
buffer.open(QIODevice.WriteOnly)
value.save(buffer, 'PNG')
state.append((key,buffer))
return state
def __setstate__(self, state):
# retrieve a QByteArray and transform it into QPixmap
qpixmap = QPixmap()
for key, buffer in state:
qpixmap.loadFromData(buffer)
self._qpixmap[key] = qpixmap但是为了将QPixmap翻译成QByteArray,我似乎需要一个QBuffer..that是不可选的,我回到了最初的问题:-(
有谁能告诉我通过将对象转换为“可选择的东西”来实现Q像素映射泡菜的方法?
谢谢
发布于 2018-03-10 09:49:15
使用下面的QDatastream更新代码
class StoreQPixmap:
def __init__(self):
# store QPixmap computed image - It is a dictionary as several images can be stored for the same picture and
# the dictionary key is the way to distinguish them
self._qpixmap = {}
def __getstate__(self):
# QPixmap is not pickable so let's transform it into QByteArray that does support pickle
state = []
for key, value in self._qpixmap.items():
qbyte_array = QByteArray()
stream = QDataStream(qbyte_array, QIODevice.WriteOnly)
stream << value
state.append((key, qbyte_array))
return state
def __setstate__(self, state):
self._qpixmap = {}
# retrieve a QByteArray and transform it into QPixmap
for (key, buffer) in state:
qpixmap = QPixmap()
stream = QDataStream(buffer, QIODevice.ReadOnly)
stream >> qpixmap
self._qpixmap[key] = qpixmaphttps://stackoverflow.com/questions/49181669
复制相似问题