top of page

UI in python using QT and PySide2

Source File is here.

There are several UI technologies in the market. Now a day’s people prefer a web UI than a desktop UI. And there is a reason for that, and it is very convenient to use those URI from anywhere from any device. But there are such applications which cannot have a web UI.


In this blog, I am not going to start a debate which type of UI is better. It’s a matter of choice and more than that nature of the application, what problem application is going to solve or who is the target audience?

The motive of this blog is to guide through the steps of UI creation in Python Using QT and PySide2.


PyQT5 is also a very trendy python package for UI creation using QT. Anyone can explore it, or I will write in future.


What is QT?

I will not go in details but from Official QT wiki:

"Qt is a cross-platform application development framework for desktop, embedded and mobile. Qt is not a programming language on its own. It is a framework written in C++."


Why I choose PySide2?

QT project has adopted PySide2 which will increase its popularity in future.

Another reason to choose PySide2 is Licensing. You need not share source code if you want to distribute your application. In the case of PyQt5, you will have to buy a commercial license.

There are no such significant differences in these two libraries in usability. Both offer almost the same features and API. If you know, PySide2 can easily work on PyQt5. I found an excellent article which explains the differences between these two libraries. I will recommend reading this article if you want to know the significant differences between Pyside2 and PyQT5. It will also help you to decide which one to use in your project.

Hope this is enough background information. Now let’s start writing our first UI in Python using QT and PySide2.


Pre-requisite:


Open QT designer. You will see a welcome page.

Open a new file and follow steps as directed.

Select Qt -> Qt Designer Form.

In the next step select “MainWindow” and follow steps as directed.

After completing all steps, a blank window will open.

Let’s create our first window and add some widgets to it.

Let’s create our first window and add some widgets to it.

Add a “Line Edit” widget from “Input Widgets” section and a “Push Button” from “Buttons” section. Save this file.

This file will get saved at the location given at the time of creation with the name given there.

If you go to the location, you will see a file, in my case, it is “firstWindow.ui”. If you open this file, you will see it is an XML file.

Now there are a couple of ways to use this file. I will take a simple way to go. Later, you can try other ways. Maybe I will explain those in my other blog.


Generate a Python file:

Now it’s time to generate a python file for this “FirstWindow.ui”

There is a tool “pyside2-uic.exe” to do that. This gets installed with PySide2 in “C:\Users\<user_name>\AppData\Local\Programs\Python\Python38-32\Scripts\”.

You can add this path to an environment variable to use it directly. If you don’t know how to add a path variable check these for Linux and Windows.

Run: pyside2-uic.exe <fileName>.ui -o <filename.py>

It will generate a file with .py extension at the same location. I will give a brief about this file later in the blog.

Now you must write down some code. No more tools.

In Main script file “BasicQTWindow.py”, import required packages as below.

from PySide2 import QtWidgets   #for QT widgets and function. 
import firstWindow

QtWidgets class is the base class of all user interface objects. The widget is the atom of the user interface, it receives mouse, keyboard and other events from the window system, and paints a representation of itself on the screen. Every widget is rectangular, and they are sorted in a Z-order. A widget is clipped by its parent and by the widgets in front of it.


import firstWindow. It has our UI class Ui_MainWindow, you created above.

Now it’s time to create a class which will handle all UI operation.

class MyWindow(firstWindow.Ui_MainWindow, QtWidgets.QMainWindow):

If I talk in terms of MVC architecture,

Class Ui_MainWindow – It is a View component of our application.

Class MyWindow – It is a Controller of our application. It will decide what to do on UI actions.

For the simplicity of this application, there is no Model component.

Let’s jump into our initializer function.

 def __init__(self, parent=None):
     super(MyWindow, self).__init__(parent)
     self.setupUi(self)
     self.setWindowTitle("MyFirstQTWindowApp")
     self.setWindowIcon(QIcon("QTIcon.png"))
     self.Push_PB.clicked.connect(self.PushButtonHandler)

The super() built-in returns a proxy object (temporary object of the superclass) that allows us to access overridden methods of the superclass.

self.setupUi(): we are calling setupUi function of superclass Ui_MainWindow.

self.setWindowTitle(): It will set a window title. This is a function in QtWidgets.

self.setWindowIcon(): Hope you understood what it will do by its name. This requires a QIcon object as a parameter. To use this class, you will have to import QIcon from Pyside2.QtGui.

self.Push_PB.clicked.connect(self.PushButtonHandler): If you remember we have a push button object Push_PB. Clicked is a mouse event and connect is to bind handler function with a mouse click. It means whenever the user click button, It will invoke PushButtonHandler function.

Now we need to write this handler function PushButtonHandler().

def PushButtonHandler(self):
        text = self.AddName_LE.text()
        QtWidgets.QMessageBox.about(self, "Namaste! "+text, "Welcome to QT world.")

On button click, PushButtonHandler() function will be invoked. It will fetch the text entered into the text box by the user and show a message box

Now it’s time to invoke our window class.

app = QtWidgets.QApplication()
MyFirstWindow = MyWindow()
MyFirstWindow.show()
app.exec_()

The QApplication class manages the GUI application’s control flow and main settings. At any time, there can be only one object of this can exist for an application, irrespective of the number of windows.

Next, we will create an object of my window class we defined above. show() has counterpart hide(). I am leaving this for the reader to explore and let me know your findings in comments.

At last, let’s execute our application.

Hope you learn something here. Maybe in the next blog, I will explain how to open a new window on a button click.



Comments


© 2023 by Dheeraj Jha

bottom of page