Create a Simple GUI in QT

Start QT Designer and select Main Window then press Create.

images/app1-1.png

Now save the file to in an empty directory with the name of app1.ui

images/app1-2.png

Open a terminal in the directory you saved app1.ui in and run the following command.

pyuic5 app1.ui -o app1.py

You will now have a file app1.py and the contents of the file describes the GUI. For now it is a simple window.

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

# Form implementation generated from reading ui file 'app1.ui'
#
# Created: Mon Jul 16 07:01:29 2018
#      by: PyQt5 UI code generator 5.2.1
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 20))
        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(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))

Now create a file called main.py in the same directory. In the terminal you opened in that directory we need to make the file main.py executable.

chmod +x main.py

Put the following in the file main.py

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
# this line imports the app1.py file, notice you need to use class name from
# the app1.py file
from app1 import Ui_MainWindow

# now we create a class of type QMainWindow using our Ui_MainWindow
class MainWindow(QMainWindow, Ui_MainWindow):
        def __init__(self):
                #super(MainWindow, self).__init__()
                super().__init__()
                self.setupUi(self)

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

if __name__ == "__main__":
        main()

Now you can run the application with the following command in the terminal.

./main.py