When we are building complex GUI applications, our codes most of the time get out of hand, and we will be overwhelmed by codes without any proper structure. In this post, I will share a code formatting structure for writing PySide2 applications. The idea is to keep the assets within the code clearly separated. Let us take the code from the previous post as an example:

class MainWindow(QtWidgets.QWidget):
    
    def __init__(self, *args):
        QtWidgets.QWidget.__init__(self, *args)
        
        self.labelName = QtWidgets.QLabel("Name")
        self.buttonTextUpdate = QtWidgets.QPushButton("Update")
        self.editText = QtWidgets.QLineEdit()
        self.setWindowTitle("Name")
        
        mainLayout = QtWidgets.QVBoxLayout()
        mainLayout.addWidget(self.labelName)
        mainLayout.addWidget(self.editText)
        mainLayout.addWidget(self.buttonTextUpdate)
        self.setLayout(mainLayout)

We can separate the different assets into multiple functions for better clarity. Below is the suggested structure:

class MainWindow(QtWidgets.QWidget):
    
    def __init__(self, *args):
        QtWidgets.QWidget.__init__(self, *args)
        self.createMenu()
        self.createComponents()
        self.createLayout()
        self.createConnects()

        self.setWindowTitle("Name")

    def createMenu(self):
        pass
        
    def createComponents(self):
        self.labelName = QtWidgets.QLabel("Name")
        self.buttonTextUpdate = QtWidgets.QPushButton("Update")
        self.editText = QtWidgets.QLineEdit()
        
    def createConnects(self):
        pass

    def createLayout(self):
        mainLayout = QtWidgets.QVBoxLayout()
        mainLayout.addWidget(self.labelName)
        mainLayout.addWidget(self.editText)
        mainLayout.addWidget(self.buttonTextUpdate)
        self.setLayout(mainLayout)

We will deal with createMenu() and createConnects() in the upcoming tutorials.

Leave a comment

Your email address will not be published. Required fields are marked *