Building an application GUI with PyQT, beginners tutorial

Standard

In this tutorial we will teach you how to create a graphical application with PyQT.  You will need to install some packages:

If python-kde4 cannot be found update your repository to find it. If you are on Ubuntu use this link.

Now we can use the QT Designer application. It saves us from writing tons of layout code that you may be used to when writing HTML.  Start qt4-designer from your applications menu. The QT Designer application will appear:

QT_Designer

QT_Designer

Press Dialog without Buttons and press Create. You can now drag any component from the widget box to the form. Simple drag and drop. We added a button, label and a pixmap.  (I took a random image from the web for the pixmap)

QT_KDE_Dialog

Our window looks like the image above. Press Form > Viewcode. We will get a popup box with the form code in… C++! That is great, but we want the Python code.   Press File > Save as > form.ui.

The file test.ui contains your form described in XML format. (You can view it in a text editor) Open a console and type:

Running the file does nothing. Create a new file called  gui.py

Paste the code below:

Run with:

This will open our graphical interface. Pressing on the OK button will simply close the application.

PyQT window

We want to add some action when the OK button is pressed.  We add these three lines to the code:

Please make sure your button is named pushButton by inspecting the form.py file. Pressing the button will print ‘OK pressed’ to the terminal.

pyqt_window2

Total application below:

gui.py

form.py (generated):

 

3 Comments

  1. > We added a button, label and a pixmap. (I took
    > a random image from the web for the pixmap)

    How do you add the pixmap? I get, that you need to
    drag and drop another label and see its pixmap property,
    but the file dialog wants a “ressource file”, which I
    don’t know where to get from.

    Dragging an image from another application didn’t work either.

    • Press the arrow that is pointing downwards next to label pixmap. (not on the dots). A small popup menu will come up with “Choose resource”, “Choose file”. Select “choose file”. Select any image from the disk. As the images below:

      https://talkera.org/python/wp-content/uploads/2015/01/pixmap1.jpg
      https://talkera.org/python/wp-content/uploads/2015/01/pixmap2.png

  2. > sudo pip install pyqt

    That won’t work. I don’t think pyqt has ever been installable with pip. Since you’re assuming a Debian based system, ‘sudo apt-get install python-qt4′ should do the trick.

Leave a comment to Amadi Click here to cancel reply.