我尝试 pickle QPolygon 并在之后加载它,但出现错误。我已经使用 PyQt4 在 Python2 上完成了此操作,但现在想在使用 PyQt5 的 Python3 上使用它。
我不想读取/加载使用 Python 2 生成的数据! pickle 文件只是用来临时存储 Qt 元素,例如从 Python3 到 Python3 的 QPolygons。
我已经为 pickle.dump() 测试了 1-4 的不同协议(protocol)选项,并尝试使用“fix_imports=True”选项,这在 Python3 中应该没有什么不同。
这是我的简化代码
from PyQt5.QtGui import QPolygon
from PyQt5.QtCore import QPoint
import pickle
file_name = "test_pickle.chip"
with open(file_name, 'wb') as f:
poly = QPolygon((QPoint(1, 1), QPoint(2, 2)))
pickle.dump(poly, f, protocol=2) # , fix_imports=True)
# loading the data again
with open(file_name, 'rb') as f:
elem = pickle.load(f, encoding='bytes') # , fix_imports=True)
我收到以下错误消息,但无法对其执行任何操作:
elem = pickle.load(f, encoding='bytes') # , fix_imports=True) TypeError: index 0 has type 'int' but 'QPoint' is expected
除了 pickle ,还有其他选择吗? 提前致谢!
最佳答案
您可以使用QDataStream
来序列化/反序列化Qt 对象:
from PyQt5 import QtCore
from PyQt5.QtGui import QPolygon
from PyQt5.QtCore import QPoint, QFile, QIODevice, QDataStream, QVariant
file_name = "test.dat"
output_file = QFile(file_name)
output_file.open(QIODevice.WriteOnly)
stream_out = QDataStream(output_file)
output_poly = QPolygon((QPoint(1, 6), QPoint(2, 6)))
output_str = QVariant('foo') # Use QVariant for QString
stream_out << output_poly << output_str
output_file.close()
input_file = QFile(file_name)
input_file.open(QIODevice.ReadOnly)
stream_in = QDataStream(input_file)
input_poly = QPolygon()
input_str = QVariant()
stream_in >> input_poly >> input_str
input_file.close()
print(str(output_str.value()))
print(str(input_str.value()))
关于python - 在 python 3.6+ 和 PyQt5 中 pickle QPolygon,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54928431/