首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何腌制QPixmap?

如何腌制QPixmap?
EN

Stack Overflow用户
提问于 2018-03-08 20:11:25
回答 1查看 487关注 0票数 0

我有一个存储要生成的QPixmap的类。我想对它进行分类,这样它就可以从一个会话重用到下一个会话,而不需要从初始图像重新计算(有一些调整大小和繁重的操作)。

QPixmap是不可选择的,所以它不能工作,但我注意到QByteArray是可选择的。因此,我尝试实现一个'getstate','setstate‘解决方案。见下文。

代码语言:javascript
复制
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像素映射泡菜的方法?

谢谢

EN

回答 1

Stack Overflow用户

发布于 2018-03-10 09:49:15

使用下面的QDatastream更新代码

代码语言:javascript
复制
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] = qpixmap
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49181669

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档