Getting Started With PyQt

PyQt is one of the two most popular Python bindings for the Qt cross-platform GUI/XML/SQL C++ framework (another binding is PySide).

If you have ever used any distribution of linux, you must have heard about Qt and GTK. Most of the desktop enviornments in linux used either of those Gui Toolkits, for example Gnome, Unity, MATE, Cinnamon etc use Gtk while KDE, Razor-Qt etc use Qt for creating Graphical interfaces.

Both Gtk and Qt are very very powerful libraries and can be used to create beautiful user interfaces also the python bindings for both of them are available.

In this post I’m writing about how to create Gui applications in python using Qt.

Tools required.

You will need following tools to build the application with GUI usig PyQt.

* Qt-devel library prefarably Qt4 or Qt5

* Qt-Designer

* PyQt, python bindings for Qt framework.

Qt-devel: Is the development package of Qt framework which contains all the header files required to access library.

Qt-Designer: Is a tool for creating and buildig graphical user interfaces with QtWidgets.

Installation

On Fedora 24 and above

$ dnf install qt5-designer qt5-devel PyQt4-devel

on Ubuntu

$ apt-get install python-qt5 pyqt-dev-tools qt5-designer

Designing the Gui

  • Start the Qt-designer from launcher or use the command
$ qt-designer5

A window like following will open.

from template formats select “Main Window” and click create.

Now you can drag and drop the widgets from the side panel onto the window you are designing.

Just for this example I’m creating a click counter. I’m putting only a button and a label on the window.

once this is done save the file and exit the qt-designer.

Convert to python code.

Now it’s time to convert this UI into the python code which can be executed.

To do that there is a tool provided by Qt called “pyuic5”.

$ pyuic5 -o <your .py file name> <your .ui file name>

The python file created by pyuic5 will contain code something like

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

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

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(481, 379)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(50, 40, 92, 36))
        self.pushButton.setObjectName("pushButton")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(50, 120, 121, 21))
        self.label.setObjectName("label")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 481, 28))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "ClickMe"))
        self.label.setText(_translate("MainWindow", "Clicked 0 Times"))

Here in class “Ui_MainWindow” two methods are created, setupUi and retranslateUi.

setupUi creates the widget objects in the proper containers and assigns the proper object names to them.

retranslateUi sets the text and titles of the widgets.

Execute this python file

Now you have the code to create the window and all the widgets you want, but to execute this code you will have to add some more code to it.

import sys
if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv) #create a new instance of QApplication
    ex = Ui_MainWindow() #create a new instance of the Ui you just cerated.
    w = QtWidgets.QMainWindow() #create an instance of QMainWindow
    ex.setupUi(w) #create your widgets inside the window you just created.
    w.show() #show the window.
    sys.exit(app.exec_()) #Exit the program when you close the application window.

Append this code to the end of your python file.

After this when you run this python file a window like following will appear

Button clicked event

To count the number of clicks, create variable “count” in the class.

self.count = 0

To “connect” the clicked event of the button to a method in the class.

self.pushButton.clicked.connect(self.incCount)

and creaet a method “incCount” in the same class.

def incCount(self):
    self.label.setText(str(count))
    self.count+=1

Once done all of the above changes the code looks like.

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

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

from PyQt5 import QtCore, QtGui, QtWidgets
import sys

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        self.count = 0
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(481, 379)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(50, 40, 92, 36))
        self.pushButton.setObjectName("pushButton")

        self.pushButton.clicked.connect(self.incCount)#connect a method to click event

        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(50, 120, 121, 21))
        self.label.setObjectName("label")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 481, 28))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "ClickMe"))
        self.label.setText(_translate("MainWindow", "Clicked 0 Times"))

    def incCount(self):
        self.label.setText(str(self.count))
        self.count+=1

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    ex = Ui_MainWindow()
    w = QtWidgets.QMainWindow()
    ex.setupUi(w)
    w.show()
    sys.exit(app.exec_())

This way you can create beautiful Gui applications using Qt framework in python.

comments powered by Disqus