Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
Resource icon

GUI class using QT Designer

This guide will not focus on usage of the Qt Creator or how widgets work. Rather it will focus on how the generated code and how it "should" be implemented so that the functionality and GUI does not "bleed into" each other. This so you get a nice clean structured project, focusing on development for apps, in this case, Main window apps.

Note! I always use PySide2 or PySide6 instead of PyQt, the reason is licencing. PyQt is a library made from a 3:d party company and If a person wants to sell apps using PyQt, that person must buy a commercial license (GPL). However, PySide was made from the previous owners of QT and it operates using a different license (LGPL). This license is modelled on the GPL but allows developers to use software components released under the LGPL in their own software, without being required to release their source code.

# QT Designer
It is a great tool to quickly and visually create a graphical user interface (GUI) without any functionality.

For the following example I created a MainWindow, containing 2 widgets, 1 label and 1 QTextEdit-box.
Pasted image 20240416115449.png


## Generated python code

Python:
# -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'info_boxTPAIDa.ui'
##
## Created by: Qt User Interface Compiler version 5.15.2
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
################################################################################

from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        if not MainWindow.objectName():
            MainWindow.setObjectName(u"MainWindow")
        MainWindow.resize(800, 604)
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName(u"centralwidget")
        self.horizontalLayout = QHBoxLayout(self.centralwidget)
        self.horizontalLayout.setObjectName(u"horizontalLayout")
        self.widget = QWidget(self.centralwidget)
        self.widget.setObjectName(u"widget")
        self.verticalLayout = QVBoxLayout(self.widget)
        self.verticalLayout.setSpacing(3)
        self.verticalLayout.setObjectName(u"verticalLayout")
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.Header_titel = QLabel(self.widget)
        self.Header_titel.setObjectName(u"Header_titel")
        
        self.verticalLayout.addWidget(self.Header_titel)
        
        self.info_text_box = QTextEdit(self.widget)
        self.info_text_box.setObjectName(u"info_text_box")
        
        self.verticalLayout.addWidget(self.info_text_box)
        
        
        self.horizontalLayout.addWidget(self.widget)
        
        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QStatusBar(MainWindow)
        self.statusbar.setObjectName(u"statusbar")
        MainWindow.setStatusBar(self.statusbar)
        
        self.retranslateUi(MainWindow)
        
        QMetaObject.connectSlotsByName(MainWindow)

    # setupUi
    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(QCoreApplication.translate("MainWindow", u"MainWindow", None))
        self.Header_titel.setText(QCoreApplication.translate("MainWindow", u"TextLabel", None))

# retranslateUi

It is important to note that all functionally for the GUI will be created separately from the generated code. The reason is, if you want to make any changes to to the GUI in QT creator and then export it again, it will overwrite the all the changes you made to that file. Therefore, it is better to not make changes to that file.


# Python GUI Class

Here is an example:

Overall, this code first imports the python generated file, called ui_info_box, that was exported from Qt Designer. It then creates a subclass InfoBox which is a QMainWindow and has the properties defined in ui_info_box. The super() function ensures that the initialization of the superclass (QMainWindow) is properly handled.

Python:
from ui import ui_info_box

from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *


class InfoBox(QMainWindow, ui_info_box.Ui_MainWindow):
    def __init__(self, parent=None):
        super(InfoBox, self).__init__(parent)
        self.setupUi(self) # init the ui file
        # rest of the classs

## Inheritance
Here, InfoBox inherits from both QMainWindow and ui_info_box. This means InfoBox will have all the attributes and methods of both QMainWindow and ui_info_box

Python:
class InfoBox(QMainWindow, ui_info_box):

## Super()

The super() function in Python is used to call methods of the superclass. It returns a proxy object that delegates method calls to a parent or sibling class. In the context of __init__ method, super() is typically used to call the constructor of the superclass.

Python:
super(InfoBox, self).__init__(parent)

This line calls the constructor of the superclass (QMainWindow) and initializes it. It passes parent as an argument to the superclass constructor.

## Initialization


In this example, the __init__ method of InfoBox is defined to initialize the InfoBox object.

Python:
def __init__(self, parent=None):     
    super(InfoBox, self).__init__(parent)
    self.setupUi(self) # init the ui file

Here, the __init__ method takes an optional parent argument and calls the constructor of the superclass (QMainWindow) using super(). This ensures that the initialization logic of the superclass is executed before any additional initialization specific to the InfoBox class.

Calling setupUi() then initializes the user interface components defined in the .ui file, setting up the layout and widgets as designed in Qt Designer.

### Support for Parent-Child Relationships
In Qt, many GUI elements can be organized into a parent-child hierarchy. When a widget (such as a window or dialog) is created, it can be assigned a parent widget. The child widget becomes visually contained within the parent widget, and it will be deleted automatically when the parent is deleted. This parameter allows for specifying the parent widget when creating an instance of the InfoBox class, facilitating the establishment of parent-child relationships.

For example, if you have a main window and want to create an instance of InfoBox as a child widget within that main window, you can pass the main window object as the parent argument:

Python:
info_box = InfoBox(parent=main_window)

By doing this, InfoBox will be contained within main_window, and its behaviour (such as deletion) will be tied to that of the parent window.

## Summary

  • The use of super() ensures that the constructor of the superclass (QMainWindow) is called properly, allowing for correct initialization of inherited attributes and methods.
  • Passing parent to the superclass constructor allows for proper parenting of the InfoBox instance within the Qt framework, which can be useful for managing widget hierarchies and memory management.
  • Calling setupUi() initializes the user interface components defined in the .ui file, setting up the layout and widgets as designed in Qt Designer.

# Result

Python:
import ui_info_box
import sys

from PySide6.QtCore import *
from PySide6.QtGui import *
from PySide6.QtWidgets import *


class InfoBox(QMainWindow, ui_info_box.Ui_MainWindow):
    def __init__(self, parent=None):
        super(InfoBox, self).__init__(parent)
        self.setupUi(self)  # init the ui file
        self.setWindowTitle("Info")

        self.Header_titel.setText("This is a Title!")
        self.info_text_box.append("Hello World!")


if __name__ == "__main__":
    app = QApplication(sys.argv)
    form = InfoBox()
    form.show()
    sys.exit(app.exec())
Pasted image 20240423074632.png

honest_work.jpg
  • Like
Reactions: tiktoksss
Author
Nidas
Views
226
First release
Last update

Ratings

0.00 star(s) 0 ratings

More resources from Nidas

Back
Top Bottom