[PyQt] Python 3 import error

Thorsten Kampe thorsten at thorstenkampe.de
Thu Dec 2 17:39:16 GMT 2010


* Hans-Peter Jansen (Thu, 2 Dec 2010 15:47:28 +0100)
> On Thursday 02 December 2010, 14:25:21 Thorsten Kampe wrote:
> > Okay, if I omit the ".toByteArray()", then the application starts
> > with Python 3 - but it doesn't work with Python 2 anymore:
> >
> > self.restoreGeometry(settings.value('Geometry'))
> > TypeError: QWidget.restoreGeometry(QByteArray): argument 1 has
> > unexpected type 'QVariant'
> >
> > Is there a way around that or do I simply have to query the Python
> > version inside the script? Or put in a try "without toByteArray()" if
> > exception, try with "toByteArray()"?!
> 
> Add this before your _first_ PyQt4 import:
> 
> # This is only needed for Python v2 but is harmless for Python v3.
> import sip
> sip.setapi('QVariant', 2)

Actually the solution for my (two) problems is... (see below)
 
> > The - hopefully - last problem with the porting to Python 3:
> > Everything seems to work fine, except closing the application through
> > the menu or toolbar (Alt+F4 works fine):
> >
> > Traceback (most recent call last):
> >   File "my_application-new.pyw", line 32, in on_actionE_xit_triggered
> >     settings.setValue('Geometry',
> > QtCore.QVariant(self.saveGeometry())) TypeError:
> > PyQt4.QtCore.QVariant represents a mapped type and cannot be
> > instantiated
> >
> > this refers to
> > def on_actionE_xit_triggered(self):
> >     settings = QtCore.QSettings()
> >     settings.setValue('Geometry',
> > QtCore.QVariant(self.saveGeometry())) self.close()

import sip
sip.setapi('QVariant', 1)

This will make PyQt4 for Python 3 behave as PyQt4 for Python and the two 
errors above are solved. Not particular pretty (more like an ugly hack) 
but it works...!

Thorsten



More information about the PyQt mailing list