python - topyobject - qvariant pyqt5

How to get the original python data from QVariant (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

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.

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


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 -*-

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.