[PyQt] PyQt book: examples now available for Python 3.1 + PyQt API 2
list at qtrac.plus.com
Thu Apr 29 09:54:09 BST 2010
I've now ported the PyQt book's examples to Python 3.1 and PyQt's API 2.
The examples do _not_ take any advantage of Python 3.1 features (except
for str.format()), or of any Qt features beyond Qt 4.2 which is the
version the book is based on.
See the very bottom of this web page for the download links:
Here are some notes on my experience of doing the porting:
I ported to Python 3.1 _first_, and then once that was working I
replaced str % with str.format(), and only then I ported to API 2.
I had to make changes to the code in relation to the following classes:
To read/write QStrings (which don't exist in API 2) using QDataStream
you must use QDataStream.readQString() and QDataStream.writeQString().
(Do _not_ use QDataStream.readString()/QDataStream.writeString() for
strings; use them for QByteArrays, bytes, and bytearrays.)
I did not find any way to read/write bools from/to QSettings. (But I
didn't spend a lot of time on this.) My solution was to store int(0) and
settings = QSettings()
happy = bool(int(settings.value("Happy")))
You can't just do bool(settings.value()) of course since QSettings seems
to store basic Python types as strings and bool("0") is True---whereas
bool(int("0")) == bool(0) == False.
I discovered that I'd often used QString methods such as .endsWith(),
.isEmpty(), .indexOf(), .lastIndexOf(), .mid(), .left(), .right(), and
.trimmed(). All these are easy to change with equivalent str methods.
The only real differences when using QTextStream were when reading since
you now get back strs rather than QStrings so must use str rather than
QString methods if you want to process them.
In a few places I'd used QVariant.to*() methods, e.g.,
QVariant.toDate(); these are no longer needed since when API 2 is in use
PyQt automatically converts to/from QVariant.
Overall I was pleasantly surprised at how straightforward the porting
was (although I didn't do much testing!). API 2 code is cleaner and
clearer than API 1 code---and more Pythonic with the use of str instead
of QString and the elimination of QVariant.
Mark Summerfield, Qtrac Ltd, www.qtrac.eu
C++, Python, Qt, PyQt - training and consultancy
"Rapid GUI Programming with Python and Qt" - ISBN 0132354187
More information about the PyQt