Open In App

Python | Introduction to PyQt5

There are so many options provided by Python to develop GUI application and PyQt5 is one of them. PyQt5 is cross-platform GUI toolkit, a set of python bindings for Qt v5. One can develop an interactive desktop application with so much ease because of the tools and simplicity provided by this library. A GUI application consists of Front-end and Back-end. PyQt5 has provided a tool called ‘QtDesigner’ to design the front-end by drag and drop method so that development can become faster and one can give more time on back-end stuff. Installation: First, we need to install PyQt5 library. For this, type the following command in the terminal or command prompt:

pip install pyqt5

If successfully installed one can verify it by running the code:



>>>import PyQt5

PyQt5 provides lots of tools and QtDesigner is one of them. For this run this command:

pip install PyQt5-tools

Create your first app –

This is a simple app having a single button in the window. After clicking that button a message will appear “You clicked me”. Let’s start.



>>> import site

>>> site.getsitepackages()

Converting .ui file into .py file:

>>> cd “C:\\Users\\……\\Programs\\Python\\Python36-32\\lib\\site-packages” [Location of sitepackages] >>> pyuic5 “C:\Users\……\FILENAME.ui”[Exact location of .ui file] -o ” C:\Users\…….\FILENAME.py” [Location where want to put .py file]

widget.signal.connect(slot)

Below is the code – 




import sys
from PyQt5 import QtCore, QtGui, QtWidgets
 
class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(400, 300)
 
        self.pushButton = QtWidgets.QPushButton(Dialog)
        self.pushButton.setGeometry(QtCore.QRect(150, 70, 93, 28))
 
        self.label = QtWidgets.QLabel(Dialog)
        self.label.setGeometry(QtCore.QRect(130, 149, 151, 31))
        self.label.setText("")
 
        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)
        
        # adding signal and slot
        self.pushButton.clicked.connect(self.showmsg)
 
    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
        self.pushButton.setText(_translate("Dialog", "Click"))
         
    def showmsg(self):
        # slot
        self.label.setText("You clicked me")
 
if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
 
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_Dialog()
 
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())


Article Tags :