How to get the original python data from QVariant

主宰稳场 提交于 2019-12-03 16:32:04

问题


I am just learning python and Qt these days. So please consider that this will be a newbie question, but I am stuck here.

import sys
from PyQt4.QtCore import *

data1 = 'string'
data2 = QVariant(data1)
data3 = data2.toPyObject()

I expected data3 is the same as data1, 'string'. However in my system data3 is

PyQt4.QtCore.QString(u'string')

It is not a big deal if the data I want to handle is simple like example, but I want to handle 'dict' type data so I need to fix this problem.

I think this is encoding problem, but can't find how to fix it.

*In every document I am declaring that:

#-*- coding: utf-8 -*-

回答1:


You can work around this issue by wrapping your data in an immutable container:

>>> from PyQt4.QtCore import QVariant
>>> data = {'key1': 123, 'key2': 456}
>>> v = QVariant((data,))
>>> v.toPyObject()[0]
{'key2': 456, 'key1': 123}



回答2:


Before you can compare data1 and data3 you need to convert the QString to Python string simply writing:

>>> same_as_data1 = str(data3)

Now you've got back the same string:

>>> data1 == data
data1 == same_as_data1
True

Wherever a string appears (as key or values) it will be mapped to QString. You can do the conversion either manually, for example:

d = QVariant({'key1':123}).toPyObject()
d_with_str_keys = dict((str(k), v) for k,v in d.iteritems())

or you can change the QString behaviour, as Avaris pointed out above.




回答3:


You can convert the dict into a string and after just eval(str) it back to a dict:

pydict  = {'key1': 'val1', 'key2': 'val2'}
variant = QtCore.QVariant( pydict )
...
pydict = eval( str( variant.toString() ) )
print pydict
>>> {'key1': 'val1', 'key2': 'val2'}

Just keep in mind the eval could fail if it's not able to convert one of the keys or values from string to dict. this can happen if you have a none built_in types (str, int, list.. ) but in your case it will work no problems.



来源:https://stackoverflow.com/questions/9257422/how-to-get-the-original-python-data-from-qvariant

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!