How to get the original python data from QVariant

三世轮回 提交于 2019-12-03 05:46:19

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}

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.

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.

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