[PyQt] Python 3 import error

Hans-Peter Jansen hpj at urpla.net
Thu Dec 2 14:47:28 GMT 2010


On Thursday 02 December 2010, 14:25:21 Thorsten Kampe wrote:
> * Phil Thompson (Thu, 02 Dec 2010 12:39:58 +0000)
>
> > On Thu, 2 Dec 2010 13:17:22 +0100, Thorsten Kampe
> >
> > <thorsten at thorstenkampe.de> wrote:
> > > So the ImportError is gone. Adding -py3 to pyrcc4 yields:
> > > Traceback (most recent call last):
> > >   File "my_application.pyw", line 63, in <module>
> > >     mainWin       = MainWindow()
> > >   File "my_application.pyw", line 19, in __init__
> > >    
> > > self.restoreGeometry(settings.value('Geometry').toByteArray())
> > > AttributeError: 'QByteArray' object has no attribute
> > > 'toByteArray'
> > >
> > > So the error is now in the main file. The actual line is
> > >
> > >    
> > > self.restoreGeometry(settings.value('Geometry').toByteArray())
> >
> > ...because the QVariant v2 API is the default with Python v3 so it
> > has already converted the QVariant to a QByteArray for you.
>
> 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)

> 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()

Please read my answer in this thread: "Sip usage problem".

Pete


More information about the PyQt mailing list