Introduction to Python GUI Programming with PyQt and Qt Designer

PyQt is a popular Python binding for the cross-platform C++ application framework, Qt. Qt Designer allows for drag-and-drop Python GUI building. This tutorial will cover how to make a basic calculator app to find the distance between two points.

I will be working with Python 3.4 and PyQt5 in this tutorial. If you are using Windows I recommend downloading the WinPython software package which includes Qt Designer, Spyder (a scientific programming IDE), the IPython console, and many integrated libraries such as NumPy, SymPy, and Matplotlib. This software package is free, portable, and very easy to use.

Get started by opening up Qt Designer, clicking ‘New’, and selecting the ‘Main Window’ option. The left side of the screen features a list of built-in widgets that can be added to your GUI. The following widgets will be used in this tutorial:

QGroupBox: group box container with a title

QLabel: a placeholder for non-editable text

QLineEdit: one-line text editor

QPushButton:command button

Select the necessary widgets and place them within the group box container. The QLineEdit widget will be used for both the input and output of values and the QPushButton widget will be used to initiate the calculation and display the answer. You can edit the text displayed by these widgets by double clicking on them. You should now have something like this:

distgui1

The ‘layout’ feature in Qt Designer will automatically arrange and resize your widgets. To apply the layout, right-click on the group box, scroll down to ‘Layout’, and select ‘Layout in Grid Layout’. Now the widgets should be neatly organized and evenly spaced.

distgui2

Select a widget and look at the Property Editor on the right side of the screen. The Property Editor features a long list of settings that can be used to customize a widget. Each widget has a name associated with it defined by the objectName property. These values will be referenced in your Python script so change the name to something memorable. The labels and group box will not be referenced by the program so they can be left on their default values.

distgui3

Once the widgets have been renamed save as ‘distgui.ui’. Qt Designer produces .ui files but your Python script will need a .py file to import from. To convert the .ui file to a .py file, use the ‘pyuic5’ function in the command prompt. Navigate the command prompt to the directory containing your .ui file and convert it to .py using the following:

pyuic5 taxgui.ui -o taxgui.py -x

This will convert and save the GUI file as a .py file in the same directory containing the .ui file. I always save my .py GUI files in the ‘notebooks’ or ‘scripts’ folders in the WinPython directory and I’ve had no issues importing these files into other Python scripts.

Now we will create a second python script that will import and launch the GUI and make the calculation. The following code should open the GUI you’ve created:

import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from distgui import Ui_MainWindow

class App(Ui_MainWindow):
    def __init__(self, dialog):
        Ui_MainWindow.__init__(self)
        self.setupUi(dialog)

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    dialog = QtWidgets.QMainWindow()
    taxgui = App(dialog)
    dialog.show()
    sys.exit(app.exec_())

Add a .clicked.connect() function within the __init__() function. This function will call another function when the QPushButton is pressed.

self.calc_pushbutton.clicked.connect(self.CalcDist)

In this example, ‘calc_pushbutton’ is the objectName of the QPushButton widget and CalcDist(self) is the function to be called.

Now add the CalcDist(self) function to the App(Ui_MainWindow) class. This function will read the the input values, perform the calculation, and print the output values to the screen. The following PyQt5 functions will be used to accomplish this:

text() – returns the current text in a QLineEdit as a string

setText() – displays a string in a QLineEdit

The complete code is displayed below:

import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from distgui import Ui_MainWindow
from math import sqrt

class App(Ui_MainWindow):
    def __init__(self, dialog):
        Ui_MainWindow.__init__(self)
        self.setupUi(dialog)
        # calculate and display distance when button is pressed
        self.calc_pushbutton.clicked.connect(self.CalcDist)

    def CalcDist(self):
        # retrieve input values from QLineEdit
        ax = float(self.ax_lineedit.text())
        ay = float(self.ay_lineedit.text())
        bx = float(self.bx_lineedit.text())
        by = float(self.by_lineedit.text())
        # calculate distance between points
        dist = sqrt((bx - ax)**2 + (by - ay)**2)
        # round and convert to string
        dist = str(round(dist, 2))
        # Display output values in QLineEdit
        self.dist_lineedit.setText(dist)                                

if __name__ == '__main__':
	app = QtWidgets.QApplication(sys.argv)
	dialog = QtWidgets.QMainWindow()
	taxgui = App(dialog)
	dialog.show()
	sys.exit(app.exec_())

Save the script as ‘distapp.py’. If you wrote the code in the Spyder IDE, you can simply run the application by running the script in the IDE. Otherwise, you can run the application through the command prompt by navigating to the directory containing ‘distapp.py’ and using the ‘python’ function:

python distapp.py

distgui4

Advertisements

One thought on “Introduction to Python GUI Programming with PyQt and Qt Designer”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s