After a successful installation of theĀ PySide2 ecosystem. We will start creating our first PySide2 application, a GUI with the main window, and we will go through the details one after another. In this post, we will create a simple application with 3 widgets.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from PySide2 import QtWidgets


def main(argv):
    app = QtWidgets.QApplication(argv)
    mainwindow = QtWidgets.QWidget()
    mainwindow.show()
    sys.exit(app.exec_())


if __name__ == "__main__":
    main(sys.argv)

Save this code in a file called myfirstapp.py and run the following command in your terminal.

python myfirstapp.py

The output is your first GUI main window.

There are four key points to the skeletal structure that we just made.

  • Line 3 & 4 show the libraries’ import, mainly PySide2.
  • The argv in line 7, 8, and 15 represents the input parameter from the command line.
  • Line 8 shows the PySide2 application launcher.
  • Line 9 & 10 show the main window frame.

Let us add content to our main window. To do that, we need to create a class MainWindow from the base class QWidget. We will create GUI-elements in the constructor of the class.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from PySide2 import QtWidgets


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")

def main(argv):
    app = QtWidgets.QApplication(argv)
    mainwindow = MainWindow()
    mainwindow.show()
    sys.exit(app.exec_())


if __name__ == "__main__":
    main(sys.argv)

After adding the MainWindow class, the new class has to be called in the main function (Line 20). However, if you run the code, there is no content to be seen because we need to add a layout for the widgets to be attached to.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from PySide2 import QtWidgets


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)


def main(argv):
    app = QtWidgets.QApplication(argv)
    mainwindow = MainWindow()
    mainwindow.show()
    sys.exit(app.exec_())


if __name__ == "__main__":
    main(sys.argv)
python myfirstapp.py (MacOS)
python myfirstapp.py (Windows 10)

Leave a comment

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