Oct 20, 2010

Python3, PyQt4 and missing QString

As I was recently adding support for Python 3 to my little trailer downloader application that I mentioned before (PyQTrailer) I encountered a strange problem with PyQt4 that only occurred in Python 3.

Let's take this simple python example:
$ python
>>> from PyQt4.QtCore import QString
That same code snippet doesn't work in python3 interpreter though:
$ python3
>>> from PyQt4.QtCore import QString
Traceback (most recent call last):
  File "", line 1, in 
ImportError: cannot import name QString
My first instinct was: Bug! Gentoo PyQt4 ebuild was doing something terrible and somehow made PyQt4 unusable in python3 interpreter. Turns out my gut instinct was wrong (once again :-) ).

PyQt4 since version 4.6 changed API of QString and QVariant for python 3.x. For QString this is due to fact that from Python 3.0, string literals are unicode objects (no need for u'unicode' magic anymore). This means that you can use ordinary Python strings in place for QString. But I wanted my QString for something like this:
  downloadClicked = pyqtSignal((QString, ))
This snippet creates Qt signals that you can then emit. Question is... How can we update this for Python 3.x? We could probably just replace QString with type(""), but for a change that wouldn't work with Python 2.x. So? Python dynamic nature to the rescue!
Edit: simplified QString definition (thanks Arfrever)
    from PyQt4.QtCore import QString
except ImportError:
    # we are using Python3 so QString is not defined
    QString = str
If we put previous code sample to the beginning of our Python file we can use QString in our code and it will keep working both in Python 3.x and Python 2.x. Case closed dear Watson.



Post a Comment
  1. Very good, thank you!

  2. Thank you, it's really helped (don't know how much time I would spend looking for the remedy if it wasn't your post...).