python - 在 python 3.6+ 和 PyQt5 中 pickle QPolygon

标签 python python-3.x pyqt5 pickle

我尝试 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/

相关文章:

python - 拆分字符串 - Python

macos - 视网膜显示的系统托盘图标大小是多少?

javascript - 如何使用pyqt5获取网页?

python - 舍入 lambda 函数

python-3.x - 是否有令人信服的理由调用 type.mro() 而不是直接迭代 type.__mro__ ?

python - tkinter 按钮命令无需单击即可运行功能?

python - 使用paintEvent 在 QLabel 中绘画

python - pandas groupby-agg 关于在没有 as_index 参数的情况下保留组列不一致

python - Django-Tastypie 中的多部分/表单数据 POST、PUT、PATCH

python - Django 在应用程序启动时运行代码但不在迁移时运行