Archive for the ‘Programming’ Category

I’ve been using PyQt for about two years now. Mark Summerfield’s books on Qt, PyQt, and Python are and have been a great help. If you program in any area he’s written on, I highly recommend checking his work out. His PyQt and first Qt book are a bit dated, but provides an awesome introduction. The new Advanced Qt Programming is great in the areas it covers, but it’s expensive and given the size of Qt, can’t cover everything. Nevertheless, it has some great work on threading and other areas that are useful. His other book on Qt using C++, C++ GUI Programming with Qt4, is definitely dated but a wonderful introduction to Qt. If you’re programming Python and PyQt, it’s still easy enough to follow conceptually and most of it translates to Python.

N.B.: The rest of this post discusses Python 3 or v3-style PyQt programming, which uses built-in Python classes to replace many Qt classes. The most prominent of this is replacing instances of QSting with Python’s str. It is my understanding that this is supported in Python 2.x, so it should still be applicable.

There are two areas of PyQt, however, where Python excels beyond that of the pace with which it can be developed. I discovered PyQt’s signal/slot model before keyword arguments, but they are both gems. PyQt handles Qt-style properties in a manner very similar to Python’s properties with only minor differences. Because of that, they didn’t make my Favorite Little-Known PyQt Features list. First up is what the PyQt documentation calls new-style signals and slots. It’s elegant, clean and simple.

With completely C++-like “old style”–as the documentation calls it–signals and slots, connecting a QToolButton to a slot would look like this:

QObject.connect(self.startButton, SIGNAL('clicked()'), self, SLOT('startDownload()'))

If we throw in a little Python, it looks like this:

QObject.connect(self.startButton, SIGNAL('clicked()'), self.startDownload)

That’s a little clearer, but it’s not “Pythonic” (I really don’t like that term, but it’s true here). Here’s how it looks using new-style signals and slots:


I’d call that a much cleaner way of doing things. We can take this a step further to support overloaded signals. Imagine a QComboBox with the currentIndexChanged() signal, which can have a QString (str in PyQt) or int parameter. Getting this to work is pretty simple, too: we index the parameter type. For example:


PyQt treats the currentIndexChanged() signal like a dict to pick which of the two signal signatures to connect, using the class type as a key.

Next up is using keyword arguments for Qt properties and signals during QObject construction. Consider how our imaginary startButton QToolButton would be constructed, C++ style:

self.startButton = QToolButton(QIcon(‘./images/start.png), ‘Start’, self)
self.startButton.setToolTip(‘Starts the download.’)

I threw in the signal connection for a reason, which I will explain in a moment. One thing that C++ features and Python lacks is method signature overloading, a necessary loss given Python’s dynamic nature and duck-typing. SIP transparently handles this for us, so PyQt still works nicely with Qt’s frequent function overloads. I mention this because of the first line, where I used the QToolButton(QIcon, QString, QObject) signature as opposed to QToolButton(QObject). It’s a small thing, but try implementing that in Python–it sucks. Consequently, some Python zealots would argue that it’s not very Pythonic. Anyway, let’s get fancy.

PyQt implements support for setting Qt properties during the Python __init__ call after creating the C++ object it wraps, and it does this via keyword arguments. To take advantage, we can just tail any property names as keywords during the constructor call. In fact, it’s even possible to completely exclude any non-keyword arguments, which I will do. Converting the above example to completely keyword argument-based __init__ call might look like this:

self.startButton = QToolButton(parent=self,
                               toolTip=’Starts the download’,
                               iconSize=QSize(32, 32),

Boom. Using this method has a number of advantages. First and most obviously, it’s faster to type. Secondly, it clusters things a little more neatly and list-like, which makes it easier to read (and modify). Also, note the signal connection on the end. I haven’t tried to use keyword arguments for overloaded signals (as in the QComboBox example) before, and I doubt it would work. I should mention a caveat I’ve run into regarding signal connection by keyword. I usually lump all of my signal and slot connections in a method I also usually call connectSignals()–I’m tricky with names like that. Doing this makes it easy to see exactly what signals/slots are connected, modify them, and selectively disable if necessary for debugging. Having an extraneous signal connected elsewhere–even if it’s for a QPushButton connected to QDialog.close()–is a little out of place. If you lump your signal connections in the same way, be aware that connecting signals by keyword argument can become an issue.

All right, that’s it for now. Happy New Year.

Qt 4.8 (and the equivalent PyQt release) came out just in time with multithreaded http support and some other functional improvements. I mention multithreaded http primarily because I’m working with QtNetwork right now, and threading a simple dialog-based application would be a pain. Thankfully, I hadn’t attempted that portion of the code writing process yet–althought I have had to design with threading in mind. I can forget about dealing with that aspect now, gratefully, and focus on getting this &@#$% to work. I redesigned a few aspects of the code, but it’s ugly enough on the internals that I’m going to need to rewrite a lot of things.

The ideas are churning, and that’s good.

I’m sitting at work (Starbucks) typing up a random blog entry to get back into the habit of the blogging phenomenon. I couldn’t tolerate the old four sidebar style, so I’ve changed the blog appearance. Development on KyUI is halted temporarily while I teach myself QtNetwork. I’ve got two new widgets to throw into the mix, one based on work from another PyQt programmer. I’ll talk about that once it’s presentable. There are other ideas churning, but I’d rather not get into them until I actually make…what’s the word?…progress.

Working with QNetworkAccessManager is interesting. I converted the PyQt-converted-from-Qt example for QHttp to QNetworkAccessManager, and the results were less than inspiring. QNAM (as I’ll abbreviate it) decided my Internet access was unavailable with a decidedly confusingly generic error message. I’m writing a tidbit of software that reads in HTML, grabs information out of it, and generates the appropriate link to a wallpaper JPEG without running through intermediary HTML. It’s teaching me QtNetwork and managing lots of signals and possible error conditions. I have to admit that–after some heavy cursing–QNetworkAccessManager is better than QHttp, particarly with the use of QNetworkReply as a QIODevice. The one feature of QHttp that I miss is using QNetworkAccessManager.get() to funnel a request directly into a QIODevice, specifically a file. Yes, QNetworkReply is an io buffer, but it would be nice if I could call get(QNetworkRequest, QFile) and wait for the finished() signal from the QNetworkReply it returns without waiting for the readyRead() signal and chunking data into the file. Just a thought.

Other thoughts: contentsMargins should be a QProperty for QWidget and QLayout. I use keyword arguments almost exclusively to set initial QObject subclass states, and not being able to set the contents margins this way is irritating.

I’m off now…into The Cloud.

A year after my blog got hacked, I’ve finally bothered to restore and fix everything; White-Walls is back!

In the time that’s passed, my interest in PyQt4 and Qt simmered into actual UI development. I turned sketches and rough designs into working code, learning a great deal in the process. I apologize to Python 2.x programmers, but Python 3 is my flavor of choice. That said, all of the code should be easily adaptable into working Python 2.7 code for those who wish.

I’ve named the project KyUI, pronounced KYOO-ee, because Q-UI was taken. The goal behind KyUI is straightforward: programmers often have to recreate the wheel for their software, which is a waste of time. There are quite a few widgets and dialogs that are common to most desktop applications but are not provided with Qt and are unavailable as source without stripping from other OSS projects. The alternative that most developers are left with is to rewrite dialogs for things like setting hotkeys, tree widget headers, and toolbar buttons. Another simple example is adding a gripper to QSplitterHandle, which is lacks one by default under most styles.

I’ll be discussing various topics here about thoughts on user-interface design, ideas I have, KyUI progress, and how-tos for writing PyQt code that goes beyond Mark Summerfield’s excellent Rapid GUI Programming with Python and Qt, including keyword arguments, a quick-and-easy solution regarding enumerators (e.g. Class.EnumValue in Class.Enumerator working without complex fussing, named tuples, or custom classes)

I’ve also done some serious hacking with Doxygen to make the result look (mostly) like Qt’s internal documentation, which is also available in the SVN source tree.

Look for more later.

I’m reading through About Face 2.0 again, in more detail. I’ve come across the author’s chapter on Verb-Object and Object-Verb thinking with respect to user interaction. His introduction explains that Verb-Object was the original method of interaction, but that WIMP changed that. His point, essentially, is that the ability to interact with multiple objects requires the programmer to handle a more Object-Verb method of thinking.

The example provided goes like this: you’re in a grocery store. You pick out a number of items to purchase. The items are objects, and purchasing them is the verb. The example explains that this is, in essence, selection, which puts a kink in the verb/object order, because multiple objects may be acted on. My first thought on reading this, before I finished, was that the act of selecting is in itself a verb, preserving Verb-Object order. The author points out that a user chooses his objects before interacting with them, such as selecting multiple files for deletion.

In my mind, this is fallacious. Yes, it appears the object is designated first, but there are caveats from all three perspectives that count: the user, the computer, and the programmer. Firstly, selection is, in itself, an action. From the perspective of the computer, Verb-Object order is maintained. Like the clipboard, the selected items are added to a stored list. When a user enters a command (Verb), the computer checks to see if items are already selected. Since the user has carefully selected a number of files, that list is called up in lieu of a single item (or none, if none had been selected). The order, in Verb-Object thinking is this: Select: Item, Select: Item, [repeat n times], Delete: Selection. Verb-Object thinking is preserved from the computer’s perspective.

From the user’s perspective, the same is true: the user does not think, “File 1, select, file 2, select, delete”. Really, the user doesn’t think about selecting individual items at all, although his behavior is still Verb-Object oriented. The thinking follows more like “select items”, which is Verb-Object, followed by “delete selection”. Again, this is Verb-Object thinking.

To the programmer, Verb-Object thinking is simply mandatory. Functions, methods, or whatever the programming language being used calls them, are in essence, verbs or commands. They are passed arguments as objects. Whether using functional or object oriented programming, the action is always first. The programmer doesn’t define actions for every object, he defines actions that are given objects.

Okay, I’m done.