[PyQt] Construct QVariant from object of user type

Phil Thompson phil at riverbankcomputing.com
Sun Apr 20 11:41:59 BST 2008


On Saturday 19 April 2008, Matt Newell wrote:
> Here is working code(though not in compilable form) that allows registering
> python classes(really any python object that has .__name__ attribute) as a
> QMetaType. Then you use qvariantFromPyObject to construct a qvariant from
> an instance of the registered type.  You use pyObjectFromQVariant to get
> the python object back.
>
> This code could be modified to provide a single QMetaType for any PyObject.
> This would allow storing any python object without having a specific type
> registered.  Specific type registration is useful for thing like
> QItemEditorFactory, so the ability to register custom types should remain.
>
> This code could quite easily be integrated into the QVariant .sip bindings
> to provide a QVariant ctor that takes any PyObject, and a QVariant function
> that returns the PyObject.
>
> Phil, are you interested in having this functionality directly in PyQt?  I
> would be willing to integrate but don't really have time to do so at the
> moment. (It would only take a few minutes to integrate, but I would have to
> update my sip and pyqt to the latest versions first)
>
> btw. The code i pasted is written to be compiled outside of a sip module,
> therefore uses a bit of hackery to get at the sip api.  This would not be
> needed if it was integrated into PyQt.
>
> >>> class A:
>
> ...     pass
> ...
>
> >>> metaTypeId = registerPythonQMetaType(A)
> >>> print metaTypeId
>
> 424
>
> >>> qv = qvariantFromPyObject(A())
> >>> qv
>
> <PyQt4.QtCore.QVariant object at 0xb7d2ec2c>
>
> >>> qv.userType()
>
> 424
>
> >>> print qv.typeName()
>
> A
>
> >>> pyObjectFromQVariant(qv)
>
> <__main__.A instance at 0xb65391ec>
>
> Matt

Yes, I'm interested but haven't had a chance to look at your code in detail.

PyQt already registers the Py_PyObject type that is used to pass Python 
objects around. Can this be used as a basis?

Phil


More information about the PyQt mailing list