在python 3.6+和PyQt5中腌制一个QPolygon [英] Pickle a QPolygon in python 3.6+ and PyQt5

查看:137
本文介绍了在python 3.6+和PyQt5中腌制一个QPolygon的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试腌制QPolygon并随后加载它,但是出现错误.我已经在带有PyQt4的Python2上完成了此操作,但现在想在带有PyQt5的Python3上使用它.

I try to pickle a QPolygon and load it afterwards, but I get an error. I have done this on Python2 with PyQt4 but want to use it now on Python3 with PyQt5.

我不想读取/加载使用Python 2生成的数据! pickle文件仅用于临时存储Qt元素,例如QPolygons从Python3到Python3.

I do not want to read/load data generated with Python 2! The pickle file is simply used to temporarily store Qt-elements like QPolygons from Python3 to Python3.

我已经为pickle.dump()测试了1-4的不同协议选项,并尝试使用"fix_imports = True"选项,该选项在Python3中不会有什么不同.

I have tested different protocol options from 1-4 for pickle.dump() and tried to use the "fix_imports=True" option which should not make a difference in 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)

我收到以下错误消息,但不能执行任何操作:

I get the following error message but can't do anything with it:

elem = pickle.load(f, encoding='bytes')  # , fix_imports=True)
TypeError: index 0 has type 'int' but 'QPoint' is expected

除了泡菜,还有其他选择吗? 预先感谢!

Is there maybe any alternative to pickle? Thanks in advance!

推荐答案

您可以使用QDataStream序列化/反序列化Qt对象:

You can use QDataStream to serialize / deserialize Qt objects:

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 3.6+和PyQt5中腌制一个QPolygon的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆