[PyQt] PyObject to QVariant and back

Phil Thompson phil at riverbankcomputing.com
Fri Mar 9 14:00:55 GMT 2012


On Thu, 08 Mar 2012 08:35:30 +0100, Benjamin Kloster
<benjamin.kloster at videlco.eu> wrote:
> Hi everyone,
> since my use case is a rather long-winded description of my predicament,

> first my question:
> 
> Are there API functions of sip that I can use to convert a PyObject* to 
> a QVariant with the appropriate type and the other way around?

No.

> Now why I could really use such functions: For our application, I've 
> written a small C++ library that serializes QVariants along with their 
> type.  I used sip to generate Python bindings to that library. Now I'd 
> like to serialize Python types that aren't natively supported by 
> QVariant, particularly instances of decimal.Decimal, tuples and maybe 
> sets. All those are boxed by sip as QVariants with the user type 
> "PyQt_PyObject" (or something like that).
> 
> For decimal.Decimal, the solution seems relatively easy. Retrieve the 
> PyObject* from the QVariant passed to my serializer, test whether it is 
> indeed a Decimal instance and if so, serialize it so that I can later 
> recognize it as a Decimal in the deserializer. There, I create a 
> PyObject* of type Decimal with the saved data, pack it in a QVariant and

> return it.
> 
> For tuples and sets, it seems a little more complicated. Since I can 
> only retrieve the elements as PyObject pointers, I can't just 
> recursively call my serialize(QVariant) function. I also can't just put 
> them in a QVariant with the "PyQt_PyObject" user type because the 
> PyObject may actually be a float, QPoint or something else that is 
> natively supported by QVariant.
> 
> Which brings us back to my above question. I have seen the 
> "qpycore_PyObject_AsQVariant" and "qpycore_PyObject_FromQVariant" in 
> QtCore/qvariant.sip, but since they don't seem to be documented 
> anywhere, I am unsure whether they are a strictly internal feature.

They are internal.

Your use case seems reasonable so I'm happy to change things to accomodate
it. It sounds like what is needed is something similar to
%ConvertToTypeCode and %ConvertFromTypeCode but that can be applied to a
type SIP already knows about (ie. QVariant) rather than as part of the
specification of a new type. Would this give you what you want?

Phil


More information about the PyQt mailing list