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.
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.


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.
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.
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.
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
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.
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 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
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.
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.
Selecting the newly created slot.

The result will now look like:

All signals and slots.
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

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

    _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.resize(250, 320)
        self.buttonBox = QtGui.QDialogButtonBox(Dialog)
        self.buttonBox.setGeometry(QtCore.QRect(10, 270, 221, 41))
        self.horizontalLayoutWidget = QtGui.QWidget(Dialog)
                QtCore.QRect(10, 40, 231, 80))
        self.horizontalLayout = QtGui.QHBoxLayout(
        self.label = QtGui.QLabel(self.horizontalLayoutWidget)
        self.lineEdit = QtGui.QLineEdit(self.horizontalLayoutWidget)
        self.label_2 = QtGui.QLabel(Dialog)
        self.label_2.setGeometry(QtCore.QRect(0, 10, 251, 20))
        self.label_3 = QtGui.QLabel(Dialog)
        self.label_3.setGeometry(QtCore.QRect(2, 190, 241, 20))


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

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:


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


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

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

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

if __name__ == "__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)

# etc

Running the application

Running this will show the following (drumroll):

Running the application.
Running the application.

How to use Groovy’s CliBuilder

I write quite some scripts at work, either for myself or for my team. I used to write these scripts in Bash, but since we are using Windows at work, it made sense to switch to a more general scripting language. Because we’re a Java shop, Groovy seemed like a natural choice. Now, it’s often very convenient to have named command-line arguments (e.g. tool --output out.ext --input in.ext) as opposed to positional arguments (e.g. tool out.ext in.ext): named arguments allow for putting the arguments in any order you want, and you can leave out optional arguments and use the defaults. Groovy’s CliBuilder makes things especially easy.

A sample program


@Grab(group='commons-cli', module='commons-cli', version='1.4')

class Main {
    static main(args) {
        CommandLineInterface cli = CommandLineInterface.INSTANCE

enum CommandLineInterface {

    CliBuilder cliBuilder

    CommandLineInterface() {
        cliBuilder = new CliBuilder(
                usage: 'weather [<options>]',
                header: 'Options:',
                footer: 'And here we put footer text.'
        // set the amount of columns the usage message will be wide
        cliBuilder.width = 80  // default is 74
        cliBuilder.with {
            h longOpt: 'help', 'Print this help text and exit.'
            n(longOpt: 'max-count', args: 1, argName: 'number',
                    'Limit the number of days shown')
            '1' longOpt: 'one', "Show today's forecast"
            '2' longOpt: 'two', "Show today's and tomorrow's forecast"
            _(longOpt: 'url', args: 1, argName: 'URL',
                    'Use given URL to query for weather.')
            D(args: 2, valueSeparator: '=', argName: 'property=value',
                    'Use value for given property.')

    void parse(args) {
        OptionAccessor options = cliBuilder.parse(args)

        if (!options) {
            System.err << 'Error while parsing command-line options.\n'
            System.exit 1

        if (options.h) {
            System.exit 0

        if (options.n) {
            // handle user's input
        if (options.'1') {
            // show weather for one day
        if (options.url) {
            URI uri = new URI(options.url)
        if (options.Ds) {
            assert options.Ds.class == ArrayList.class

When invoked with groovy weather.groovy --help, the program will output:

usage: weather []
 -1,--one                  Show today's forecast
 -2,--two                  Show today's and tomorrow's forecast
 -D        Use value for given property.
 -h,--help                 Print this help text and exit.
 -n,--max-count    Limit the number of days shown
    --url             Use given URL to query for weather.
And here can we put footer text.

You can specify short and long names: cliBuilder.n specifies that the program will accept an argument -n. To also specify a long name, we add longOpt: max-count. To use only a long name, we can replace the short name by _: cliBuilder._(longName: 'wow-such-long'). Note that cliBuilder._ can be reused several times (in contrast to other short names).

The number of arguments can be indicated by using the args parameter. If you use more than one parameter, a valueSeparator must be indicated, which is used to split up the argument. I found that the number assigned to args is not very strict: when called with argument -Dmyprop, the following is valid.

assert options.Ds == ['myprop']

Note how we append an s to the option name (options.Ds) to get a list of properties and values. A normal invocation groovy weather.groovy -Dpancakes=yesplease would result in:

assert options.Ds == ['pancakes', 'yesplease']

When required: true is set, the program will shout at you if the argument is not used. For example, if we specify cliBuilder.q(required: true) but fail to provide the -q argument on the command line, the program will exit with error: Missing required option: q.

One thing to remember is that, if you want to use digits as argument names, you have to stringify them first by putting quotation marks around them: cliBuilder.'1'.

More on CliBuilder

Check the Groovy documentation on CliBuilder for more .


Groovy’s CliBuilder depends on cli-commons:


dependencies {
    compile group: 'commons-cli', name: 'commons-cli', version: '1.4'

Using Groovy’s AntBuilder to zip and unzip files

Suppose we need to zip a bunch of Python files (without their compiled counterparts *.pyc). The next (admittedly contrived) example shows how we could go about doing something like this in Groovy:

File srcDir = new File('/home/neftas/Downloads/scripts/')
File destDir = new File(srcDir, 'antexample')
File zippedFile = new File(srcDir, 'antzipped.zip')

def allPythonFilenames = srcDir.list().sort().findAll { it.endsWith('.py') }
assert ['a.py', 'b.py', 'c.py'] == allPythonFilenames

def ant = new AntBuilder()

ant.with {
    echo 'begin zipping and unzipping'
    zip(destfile: zippedFile, basedir: srcDir, includes: '*.py')
    mkdir(dir: destDir)
    unzip(src: zippedFile, dest: destDir)
    echo 'done zipping and unzipping'

// zip file is created
assert zippedFile.exists()
// contents of zip file should match content of source directory
def commands = ['bash', '-c', "zipinfo -1 ${zippedFile.name}"]
def process = commands.execute(null, srcDir)
def contentsOfZip = process.text.split(System.lineSeparator)
assert contentsOfZip.sort() == allPythonFilenames

// all files should be unpacked from the zip into the right directory
assert destDir.list().sort() == allPythonFilenames

ant.with {
    echo 'deleting created files'
    // notice nested Ant task
    delete(includeEmptyDirs: true) {
        fileset(dir: destDir)
        fileset(file: zippedFile)
    echo 'deleted created files'

We can use all the power of Ant in our Groovy scripts. Ant task names map to Groovy methods (see the zip method above) and the attributes are passed as maps to these methods. What’s even better, there is no need to stringify the arguments of these attributes (as is required in Ant’s XML), but we can directly use the correct datatypes (e.g. in the key-value pair destfile: zippedFile, zippedFile is of type java.util.File). All attributes of Ant tasks are available to use with AntBuilder (see Ant manual for zip task).

To use nested Ant tasks, we create closures, so that Ant’s:

<delete includeEmptyDirs="true">
    <fileset dir="lib">
    <fileset file="file.ext">

results in the following Groovy code:

ant.delete(includeEmptyDirs: true) {
    fileset(dir: 'lib')
    fileset(file: 'file.ext')

Invoking from Gradle

AntBuilder is also available in Gradle. This will come in handy when you don’t know the "Gradle way" of doing something, but do know how to tackle it in Ant.


Groovy (and Gradle) come with a bundled version of AntBuilder, so you should be good shape when creating a Groovy script, but if you want to use AntBuilder in a project, you should add ant and ant-launcher to your build.gradle:

dependencies {
    compile group: 'ant', name: 'ant',  version: '1.7.0'
    compile group: 'ant', name: 'ant-launcher',  version: '1.6.5'