[PyQt] Construct QVariant from object of user type

Matt Newell newellm at blur.com
Sat Apr 19 01:10:30 BST 2008

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
>>> qv = qvariantFromPyObject(A())
>>> qv
<PyQt4.QtCore.QVariant object at 0xb7d2ec2c>
>>> qv.userType()
>>> print qv.typeName()
>>> pyObjectFromQVariant(qv)
<__main__.A instance at 0xb65391ec>

-------------- next part --------------
A non-text attachment was scrubbed...
Name: qmetatype_python_code.cpp
Type: text/x-c++src
Size: 5112 bytes
Desc: not available
Url : http://www.riverbankcomputing.com/pipermail/pyqt/attachments/20080419/080bac33/qmetatype_python_code.bin

More information about the PyQt mailing list