2017-05-30 203 views
0

這是一個泡菜。我試圖將我的窗口/其他元素保存爲json格式,以便我可以在一個位置爲我的窗口存儲多個數據/ etcPyQt5將QByteArray保存爲json格式

我知道QByteArray具有以下功能: std :: string QByteArray :: toStdString()const的 和 的QByteArray的QByteArray :: fromStdString(常量的std :: string & STR)

這應該允許我這樣做,但到目前爲止,我不能讓它在Python工作。 關於我的一些信息在這裏找到(C)> Correct way to losslessly convert to and from std::string and QByteArray

我試圖做這樣的事情:

print(self.saveGeometry()) 
bar = self.saveGeometry() 
print(bytes(str(bar).encode())) 

轉換的QByteArray字節組到那個然後我可以保存爲字符串,但我越來越

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd9 in position 1: invalid continuation byte 

可以any1建議如何使用本機QT5 5.4+函數來保存QByteArray到QByteArray.toStdString到json然後加載json>到QByteArray.fromStdString>到幾何或其他方法?

謝謝!

回答

2

JSON無法序列化bytes/bytearray對象,因此您需要將它們轉換爲unicode對象。這意味着有必要對包含在QByteArray中的原始字節數據進行「解碼」。一種方法是先將字節轉換爲某種ASCII兼容格式,以避免任何Unicode錯誤:

>>> g = widget.saveGeometry() 
>>> d = json.dumps(bytes(g.toHex()).decode('ascii')) 
>>> x = QByteArray.fromHex(bytes(json.loads(d), 'ascii')) 
>>> x == g 
True 
+0

非常感謝!我甚至得到了Hex(),但無法實現它,非常感謝你的答案! – Dariusz