How to get the original python data from QVariant

Jonas Hong picture Jonas Hong · Feb 13, 2012 · Viewed 11.8k times · Source

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

Answer

ekhumoro picture ekhumoro · Feb 13, 2012

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}