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

Phil Thompson phil at riverbankcomputing.com
Thu Aug 14 22:41:28 BST 2008


On Wed, 13 Aug 2008 12:37:02 -0700, "Erick Tryzelaar"
<idadesub at users.sourceforge.net> wrote:
> 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() ==
> QVariant(QDateTime(...)).toDateTime()[0]
> 
> 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),
> QVariant("abc")
> 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?

I'll add it to the TODO list - though the longer term aim is to get rid of
QVariant completely.

Phil



More information about the PyQt mailing list