[PyQt] Using QVariant.toPyObject to wrap the to* functions

Erick Tryzelaar idadesub at users.sourceforge.net
Wed Aug 13 20:37:02 BST 2008

Hello again,

In our code right now, we keep having to extract data from a QVariant,
and we end up with a lot of copies of:

if v.type() == QVariant.Int:
elif v.type() == QVariant.String:

We don't really care exactly what the type is, but we have to do this
in order to work directly with the values. Since there's already a
QVariant.toPyObject that can extract arbitrary python objects, it
seems like it wouldn't be that much extra work to extend it to be able
to extract all the QVariant standard types as well. I'd guess that the
implementation could just be abstracting out the first stage of
translation, like this:

QVariant(1).toPyObject() == QVariant(1).toInt()[0]
QVariant(QDateTime(...)).toPyObject() ==

and etc. This makes QVariant a little more pythonic to me, in my opinion.

I also thought about making the QVariant.List types probably shouldn't
recursively convert the types, as in:

# assume v is a c++ QVariant that has QVariantList of QVariant(1),
v.toPyObject() == [1, "abc"]

Since in some cases you might actually want all the contained QVariant
object returned. You could always do:

[x.toPyObject() for x in v.toPyObject()]

Would anyone else find this useful?

More information about the PyQt mailing list