在QMovie中加载动画gif数据

问题描述:

我对Qt(特别是PySide)很陌生,我正在尝试编写一个脚本,将动画gif从文件加载到QByteArray,然后加载到QMovie.从文件转到QByteArray的原因是因为我无法将该gif文件保留在内存中.我希望能够以某种方式存储动画gif,以便以后可以将其写出到JSON文件中(因此QByteArray).我尝试使用此处中的ekhumoro的答案尽管未显示任何错误,但动画gif也未显示. (那里可能有东西,但我什么也看不到.)简而言之,我的代码如下所示:

I'm very new to Qt (specifically PySide) and I'm trying write a script that loads an animated gif from file into a QByteArray and then into a QMovie. The reason for going from file to the QByteArray is because I cannot keep that gif file in memory. I want to be able to store the animated gif in such a way that it can be written out to a JSON file later (hence the QByteArray). I've tried using ekhumoro's answer from here and although no errors showed up, the animated gif also doesn't show up. (There could be something there but I don't see anything.) My code, in a nutshell, looks like this:

data = open("img.gif", "rb").read()
self.bArray = QtCore.QByteArray(data)
self.bBuffer = QtCore.QBuffer(self.bArray)
self.bBuffer.open(QtCore.QIODevice.ReadOnly)
self.movie = QtGui.QMovie(self.bBuffer, 'GIF')
self.movieLabel.setMovie(self.movie) # a QLabel
self.movie.start()

我想稍后将self.bArray的内容存储到JSON文件中.

I want to store the contents of self.bArray to a JSON file later.

当我给QMovie构造函数指定文件路径时,我可以看到动画的gif,但是我无法将gif的内容保存到JSON文件中.

I can see the animated gif when I give the QMovie constructor the file path but then I won't be able to save the contents of the gif to a JSON file.

我想知道是没有正确读取数据还是没有正确地将数据传递给QMovie.

I'm wondering if the data is not being read in properly or not being passed to QMovie properly.

有什么想法吗?

谢谢!

这看起来像是PySide错误,因为相同的代码在PyQt中工作得很好.

This looks like a PySide bug, as the same code works perfectly fine in PyQt.

该错误似乎在QMovie构造函数中,该构造函数不会从传递给它的设备中读取任何内容.解决方法是显式设置设备,如下所示:

The bug seems to be in the QMovie constructor, which does not read anything from the device passed to it. A work-around is to set the device explicitly, like this:

import sys
from PySide import QtCore, QtGui
# from PyQt4 import QtCore, QtGui

app = QtGui.QApplication(sys.argv)

data = open('anim.gif', 'rb').read()
a = QtCore.QByteArray(data)
b = QtCore.QBuffer(a)

print('open: %s' % b.open(QtCore.QIODevice.ReadOnly))

m = QtGui.QMovie()
m.setFormat('GIF')
m.setDevice(b)

print('valid: %s' % m.isValid())

w = QtGui.QLabel()
w.setMovie(m)
m.start()

w.resize(500, 500)
w.show()
app.exec_()

print('pos: %s' % b.pos())