【问题标题】:How can i pickle QPixmap我怎样才能腌制QPixmap
【发布时间】:2018-03-08 20:11:25
【问题描述】:

我有一个存储 QPixmap 的类,这些 QPixmap 由 cpu comsumming 生成。我想腌制它,以便它可以从一个会话重用到下一个会话,而无需从初始图像重新计算(有一些调整大小和繁重的操作)。

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 是不可挑选的,我又回到了最初的问题 :-(

谁能告诉我通过将对象转换为“可挑选的东西”来实现 Qpixmap pickle 的方法是什么

谢谢

【问题讨论】:

  • 您返回的列表应该包括字节数组,而不是缓冲区。此外,您应该创建一个新的字节数组并缓冲循环的每次迭代。
  • 如果要序列化像素图,请使用QDatastream。
  • 谢谢大家。它确实适用于 QDatastream。代码改编如下

标签: python-3.x pyqt5 pickle qpixmap


【解决方案1】:

使用下面的 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] = qpixmap

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-10
    • 1970-01-01
    • 2020-04-12
    • 1970-01-01
    • 2023-01-28
    • 2018-07-09
    • 2016-11-25
    • 2016-11-24
    相关资源
    最近更新 更多