Relentless Coding

A Developer’s Blog

Tutorial Rapid GUI Development With Qt Designer and PyQt

Confession: I am the opposite of the lazy coder. I like doing things the hard way. Whether it’s developing Java in Vim without code completion, running JUnit tests on the command line (don’t forget to specify all 42 dependencies in the colon-separated classpath!), creating a LaTeX graph that looks “just right”, or writing sqlplus scripts instead of using SQL Developer (GUIs are for amateurs), I always assumed that doing so would make me a better programmer.

So when I was just a fledgling programmer, and I had to design and create some dialog windows for a side project of mine (an awesome add-on to AnkiSRS written in Python and Qt), I did what I always do: find a good resource to learn PyQt and then code everything by hand. Now, since Python is a dynamic language and I used to develop this add-on in Vim, I had no code completion whatsoever, and only the Qt documentation and that tutorial to go by. Making things even more interesting, is that the documentation on Qt is in C++, and is full of stuff like this:

Qt documentation with very readable C++ code for the Python
novice.

Obviously, I had no idea what all the asterisks and ampersands meant and had to use good-old trial and error to see what would stick in Python. Now, on the plus side, I experimented quite a lot with the code, but not having code completion makes it really hard to learn the API. (And even now, using PyCharm, code completion will not always work, because of Python being a dynamically-typed language and all. I am still looking at the Qt documentation quite a bit.)

One thing I noticed, though, is that the guy who develops Anki, Damien Elmes, had all these .ui files lying around, and a bunch more files that read: “WARNING! All changes made to this file will be lost!”. Ugh, generated code! None of the dedicated, soul-cleansing and honest hard work that will shape you as a software developer. It goes without saying I stayed far away from that kind of laziness.

It took me some time to come around on this. One day, I actually got a job as a professional software developer and I had much less time to work on my side-projects. So, when I wanted to implement another feature for my Anki add-on, I found I had too little time to do it the old-fashioned way, and decided to give Qt Designer a go. Surprisingly, I found out it can actually help you tremendously to learn how Qt works (and also save you a bunch of time). Qt Designer allows you to visually create windows using a drag-and-drop interface, then spews out an XML representation of that GUI, which can be converted to code. That generated code will show you possibilities that would have taken a long time and a lot of StackOverflowing to figure out on your own.

So, to help other people discover the wonders of this program, here is a little tutorial on how to do RAD and how to get a dialog window up and running with Qt Designer 4 and Python 3.

Installation

First, we need to install Qt Designer. On Arch Linux, it’s part of the qt4 package and you’ll also need python-pyqt4 for the Python bindings. (On Ubuntu, you have to install both qt4-designer and the python-qt4 packages.)

Our goal

Our goal is to create a simple dialog window that has a text input field where we can type our name, and have a label that will display “Hello there, $userName”. Yes, things will be that exciting. Along the way, we will learn how to assign emitted signals to slots and how to handle events.

Creating a dialog

Fire up Qt Designer, and you will be presented with a “New form” dialog (if you do not see it, go to File > New…).

Qt Designer’s “new form”
dialog.

For this tutorial, we are going to choose a fairly small “Dialog with Buttons Bottom”:

The main window of Qt
Designer.

To the left are the widgets that we can add to our freshly created dialog, to the right, from top to bottom, we see the currently added widgets, the properties of those widgets and the signals and slots currently assigned to the dialog window.

I’m going to add a text label and a so-called line editor to our widget. To make sure they will align nicely, I will put them together in a horizontal container, a QHBoxLayout:

A horizontal box layout with a text label and a line
editor.

In the object inspector, we can see the hierarchy of added widgets:

The object-inspector
view

This is all simple drag-and-drop: we select a widget from the left pane, drag it to the desired location in the dialog and release the mouse.

Finally, we add two more label: one at the top, instructing the user what to do, and a second one near the bottom, where we soon will display our message.

Two more text labels.

Qt Designer provides an easy way to connect signals to slots. If you go to Edit > Edit Signals/Slots (or press F4) you will be presented with a graphical overview of the currently assigned signals and slots. When we start out, the button box at the bottom already emits two signals: rejected and accepted, from the Cancel and Ok button respectively:

The signals and slots of the button
box.

The signals rejected() and accepted() are emitted when the cancel and OK buttons are clicked respectively, and the ground symbols indicate the object that is interested in these signals: in this case the dialog window itself. Signals are handled by slots, and so the QDialog will need to have slots for these signals. The slots (or handlers) are named reject() and accept() in this instance, and since they are default slots provided by Qt, they already exist in QDialog, so we won’t have to do anything (except if we want to override their default behavior).

What we want to do now is “catch” the textEdited signal from the line editor widget and create a slot in the dialog window that will handle it. This new slot we’ll call say_hello. So we click the line editor widget and drag a line to anywhere on the dialog window: a ground symbol should be visible:

Assigning a signal to a
slot

In the window that appears now, we can select the signal that we are interested in (textEdited) and assign it to a predefined slot, or we can click on Edit… and create our own slot. Let’s do that:

Creating a new
slot.

We click the green plus sign, and type in the name of our new slot (say_hello):

Selecting the newly created
slot.

The result will now look like:

All signals and
slots.

In Qt Designer, you can preview your creation by going to Form > Preview… (or pressing Ctrl + R). Notice, however, that typing text in the line editor won’t do anything yet. This is because we haven’t written any implementation code for it. In the next section we will see how to do that.

You can also see the code that will be generated by going to Form > View code…, although this code is going to be in C++.

Okay, enough with designing our dialog window, let’s get to actual Python coding.

Generating code (or not)

When we save our project in Qt Designer, it will create a .ui file, which is just XML containing all the properties (widgets, sizes, signals & slots, etc.) that make up the GUI.

PyQt comes with a program, pyuic4, that can convert these .ui files to Python code. Two interesting command-line options are --preview (or -p for short), that will allow you to preview the dynamically created GUI, and --execute (or -x for short), that will generate Python code that can be executed as a stand-alone. The --output switch (or -o) allows you to specify a filename where the code will be saved.

In our case, creating a stand-alone executable is not going to work, because we have added a custom slot (say_hello) that needs to be implemented first. So we will use pyuic4 to generate the form class:

$ pyuic4 relentless_dialog.ui -o relentless_dialog.py

This is the result:

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'relentless_dialog.ui'
#
# Created by: PyQt4 UI code generator 4.12.1
#
# WARNING! All changes made in this file will be lost!

from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(
                context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName(_fromUtf8("Dialog"))
        Dialog.resize(250, 320)
        self.buttonBox = QtGui.QDialogButtonBox(Dialog)
        self.buttonBox.setGeometry(QtCore.QRect(10, 270, 221, 41))
        self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
        self.buttonBox.setStandardButtons(
                QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)
        self.buttonBox.setObjectName(_fromUtf8("buttonBox"))
        self.horizontalLayoutWidget = QtGui.QWidget(Dialog)
        self.horizontalLayoutWidget.setGeometry(
                QtCore.QRect(10, 40, 231, 80))
        self.horizontalLayoutWidget.setObjectName(
                _fromUtf8("horizontalLayoutWidget"))
        self.horizontalLayout = QtGui.QHBoxLayout(
                self.horizontalLayoutWidget)
        self.horizontalLayout.setMargin(0)
        self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
        self.label = QtGui.QLabel(self.horizontalLayoutWidget)
        self.label.setObjectName(_fromUtf8("label"))
        self.horizontalLayout.addWidget(self.label)
        self.lineEdit = QtGui.QLineEdit(self.horizontalLayoutWidget)
        self.lineEdit.setObjectName(_fromUtf8("lineEdit"))
        self.horizontalLayout.addWidget(self.lineEdit)
        self.label_2 = QtGui.QLabel(Dialog)
        self.label_2.setGeometry(QtCore.QRect(0, 10, 251, 20))
        self.label_2.setObjectName(_fromUtf8("label_2"))
        self.label_3 = QtGui.QLabel(Dialog)
        self.label_3.setGeometry(QtCore.QRect(2, 190, 241, 20))
        self.label_3.setObjectName(_fromUtf8("label_3"))

        self.retranslateUi(Dialog)
        QtCore.QObject.connect(self.buttonBox,
                               QtCore.SIGNAL(_fromUtf8("accepted()")),
                               Dialog.accept)
        QtCore.QObject.connect(self.buttonBox,
                               QtCore.SIGNAL(_fromUtf8("rejected()")),
                               Dialog.reject)
        QtCore.QObject.connect(
                self.lineEdit,
                QtCore.SIGNAL(_fromUtf8("textChanged(QString)")),
                Dialog.say_hello)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        Dialog.setWindowTitle(_translate("Dialog", "Dialog", None))
        self.label.setText(_translate("Dialog", "Name:", None))
        self.label_2.setText(_translate(
                             "Dialog",
                             "<html><head/><body><p align="center">" +
                             "Please enter your name</p></body></html>",
                             None))
        self.label_3.setText(_translate(
                             "Dialog",
                             "<html><head/><body><p align="center">" +
                             "[Where our message will appear]" +
                             "</p></body></html>",
                             None))

It is here that you can learn a lot about how PyQt works, even though some statements seem a bit baroque, like the binding of the textChanged signal to our custom slot:

QtCore.QObject.connect(
        self.lineEdit,
        QtCore.SIGNAL(_fromUtf8("textChanged(QString)")),
        Dialog.say_hello)

If you would write this yourself, you would probably prefer:

self.lineEdit.textChanged[str].connect(Dialog.say_hello)

(Incidentally, the text between the square brackets in textChanged[str] indicates that a single argument of this type is passed to the slot.)

Bringing it all together

Having generated our form class, we can now create a base class that will use this class:

import sys
from PyQt4 import QtGui
from relentless_dialog import Ui_Dialog

class MyDialog(QtGui.QDialog):
    def __init__(self):
        super(MyDialog, self).__init__()
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)
        self.show()

    def say_hello(self, user_text):
        text = "Hello there, {0}!".format(user_text)
        self.ui.label_3.setText(text)

def main():
    app = QtGui.QApplication(sys.argv)
    dialog = MyDialog()
    app.exec_()

if __name__ == "__main__":
    main()

When we are passing self to self.ui.setupUi, we are passing the widget (a QDialog) in which the user interface will be created.

We implement our custom slot by defining a method say_hello that takes a single argument (the user-provided text from the line editor). We craft a witty sentence with it, and set it as the label text.

As mentioned before, we could also dynamically create the GUI directly from the .ui file:

import sys
from PyQt4 import QtGui
from PyQt4 import uic

class MyDialog(QtGui.QDialog):
    def __init__(self):
        super(MyDialog, self).__init__()
        dialog = uic.loadUi("relentless_dialog.ui", self)
        dialog.show()

# etc

Running the application

Running this will show the following (drum roll):

Running the
application.