Python 3 - PySide2 - Setting up and using Qt Designer

PySide2 is a Python API for the Qt framework.

This API is made with Shiboken2, the Python binding generator.

It means that you can write your code in Python and use the Qt framework as you’d do with C++.

Even building a GUI with the Qt Designer is possible.

So what do we wait to start using it?

First of all

We need to install Python 3 on your computer.

So in order to have the exact same software and libraries installed in the exact same locations, I suggest to follow the following tutorial:

Yes it's for Windows, but if you are using another OS I guess you'll be able to adapt it.

Installing PySide2 and Shiboken2

You are maybe wondering why PySide2 and not PySide?

It's because PySide is for Qt 4 and PySide2 for Qt 5.

Same thing with Shiboken2 (for Qt 5) and Shiboken (for Qt 4).

Now that you have Python on your OS, let's install PySide2 and Shiboken2.

It's actually quite easy, just open a console and type the following:

  • python -m pip install PySide2

You'll get this message:

Collecting PySide2

  Downloading https://files.pythonhosted.org/packages/e9/0c/9574f74fa125bacb101dfde825f944b567f838d48e56cf7ee02c7fe94e87/PySide2-5.13.2-5.13.2-cp35.cp36.cp37-none-win_amd64.whl (122.1MB)

     |████████████████████████████████| 122.2MB 

Collecting shiboken2==5.13.2

  Downloading https://files.pythonhosted.org/packages/5a/c8/2b5c3e29755d862a504c8e225812d2049964a047f3656684577e9e472d8a/shiboken2-5.13.2-5.13.2-cp35.cp36.cp37-none-win_amd64.whl (2.1MB)

     |████████████████████████████████| 2.1MB 

Installing collected packages: shiboken2, PySide2

Successfully installed PySide2-5.13.2 shiboken2-5.13.2

You have now PySide2 and Shiboken2 ready to be used.

There are installed at this location:

  • C:\soft\python37\Lib\site-packages

Shiboken2 won't be used in this tutorial, indeed PySide2 comes already generated with all what we need.

To be more precise, Shiboken2 is like Boost.Python, that is a wrapper to generate API from C++ code and to be used with Python.

So we'll use here PySides2 directly without compiling or generating it.

First code for Hello world

Let's now test our new toys in order to check it everything is working as expected.

Unlike with C++, there is absolutely nothing to compile.

What you have to do is just to create a new file and write some lines of code.

So to stay synchronized with this tutorial let's create a Python file at this location:

  • C:\dev\py\pyside2\badprog_tutorial\project1\BadprogHello.py

A classic, our dear Hello World from PySide2:

# badprog.com
import sys

#
from PySide2.QtWidgets  import QApplication, QMainWindow

#
class MainWindow(QMainWindow):
    #
    def __init__(self):
        #
        QMainWindow.__init__(self)
        self.setWindowTitle("Hello World from Badprog :D")
        self.setFixedWidth(500)
        self.setFixedHeight(500)
 
#
if (__name__ == '__main__'):
    app = QApplication(sys.argv)
    mainWindow = MainWindow()
    mainWindow.show()
    sys.exit(app.exec_())
 

 

To execute this file, open a console in this directory:

  • C:\dev\py\pyside2\badprog_tutorial\project1\

Then type in your console:

  • python BadprogHello.py

The Qt window should appear.

If yes then PySide and Qt framework are ready to go further on your computer.

Using the Qt Designer

OK, our Hello World example was very rudimentary.

Lets' try to create a window from the Qt Designer and use it with Python.

As you installed Qt framework (with PySides2) you have also installed the Qt Designer.

Open the following file by double clicking it:

  • C:\soft\python37\Lib\site-packages\PySide2\designer.exe

The Qt Designer is now open.

An important note here, this Qt Designer is exactly the same as the one used with C++.
So don't worry, the final result will be exactly the same with Python.

Let's create a new file.

From Qt Designer > File > New > Main Window > Create.

Saved this file in the following directory:

  • C:\dev\py\pyside2\badprog_tutorial\project_gui\

And give it the name: BadprogWindow.ui

So you have now this new file on your computer:

  • C:\dev\py\pyside2\badprog_tutorial\project_gui\BadprogWindow.ui

Let’s add some Widgets on this window (from the left pane of Qt Designer) by just clicking and moving them onto the BadprogWindow.ui.

For this example I added a Push Button and a Label.

So their respective name are by default pushButton and label.

Let is like that and save this file.

Here the code of this BadprogWindow.ui file:

BadprogWindow.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>800</width>
    <height>600</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralwidget">
   <widget class="QPushButton" name="pushButton">
    <property name="geometry">
     <rect>
      <x>230</x>
      <y>170</y>
      <width>75</width>
      <height>23</height>
     </rect>
    </property>
    <property name="text">
     <string>PushButton</string>
    </property>
   </widget>
   <widget class="QLabel" name="label">
    <property name="geometry">
     <rect>
      <x>240</x>
      <y>80</y>
      <width>47</width>
      <height>13</height>
     </rect>
    </property>
    <property name="text">
     <string>TextLabel</string>
    </property>
   </widget>
  </widget>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>800</width>
     <height>21</height>
    </rect>
   </property>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
 </widget>
 <resources/>
 <connections/>
</ui>

 

As you can see this UI file is an XML one.

So how to tell Python that we want this XML file becoming a GUI one?

It’s where PySide2 will help us by providing some useful tools such as:

  • C:\soft\python37\Scripts\pyside2-uic.exe

To use it you have to open it from a console.

So open a console in the following location (where you saved your UI file):

  • C:\dev\py\pyside2\badprog_tutorial\project_gui\

And type this command directly in your console:

pyside2-uic.exe BadprogWindow.ui > BadprogWindow.py

Here we are saying to PySide2 to create a new Python file BadprogWindow.py from the UI file.

Now open this new file generated:

BadprogWindow.py

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

# Form implementation generated from reading ui file 'BadprogWindow.ui',
# licensing of 'BadprogWindow.ui' applies.
#
# Created: Wed Nov 27 21:57:58 2019
#      by: pyside2-uic  running on PySide2 5.13.2
#
# WARNING! All changes made in this file will be lost!

from PySide2 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(selfMainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(2301707523))
        self.pushButton.setObjectName("pushButton")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(240804713))
        self.label.setObjectName("label")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0080021))
        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(selfMainWindow):
        MainWindow.setWindowTitle(QtWidgets.QApplication.translate("MainWindow""MainWindow"None, -1))
        self.pushButton.setText(QtWidgets.QApplication.translate("MainWindow""PushButton"None, -1))
        self.label.setText(QtWidgets.QApplication.translate("MainWindow""TextLabel"None, -1))

 

 

This time it's a Python code.

This file contains a class:

  • Ui_MainWindow()

And 2 methods:

  • setupUi()
  • retranslateUi()

We'll use the first method (setupUi) in our example below.

Let's create now a third file called BadprogMain.py for our main code:

BadprogMain.py

# badprog.com
import sys

#
from PySide2.QtWidgets  import QApplication, QMainWindow
from BadprogWindow      import Ui_MainWindow

#
class MainWindow(QMainWindowUi_MainWindow):
    #
    def __init__(self):
        #
        QMainWindow.__init__(self)

        #
        self.setupUi(self)
        self.connectMe()

        #
        self.setWindowTitle("Hello World from Badprog :D")
        self.setFixedWidth(500)
        self.setFixedHeight(500)

    #
    def connectMe(self):
        self.pushButton.clicked.connect(self.slotButton)
 
    #
    def slotButton(self):
        self.label.setText("Hello from Badprog :D ")
 
#
if (__name__ == '__main__'):
    app = QApplication(sys.argv)
    mainWindow = MainWindow()
    mainWindow.show()
    sys.exit(app.exec_())

 

Here we are, we have now our 3 files ready to be used.

So if you made some modifications on your BadprogWindow.ui file, you'll have to regenerate the BadprogWindow.py.

Otherwise modifications won't be applied.

Then simply execute your third file BadprogMain.py directly from its directory:

  • C:\dev\py\pyside2\badprog_tutorial\project_gui\

Open a console then type:

  • python BadprogMain.py

The window from Qt framework is displayed with a PushButton and a Label.

Click this PushButton to see the text Label change from TextLabel to Hello from Badprog :D.

Conclusion

If you are a C++ and Qt user you certainly found this example very pleasant to setup.

And if you are a Python programmer, you probably discovered how to create your first Window with Qt and PySide2.

Anyway, good job, you did it. cool

 

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.