Site icon DataFlair

Python PyQt5 Tutorial – Example and Applications

Python course with 57 real-time projects - Learn Python

Today, we will explore Python PyQt5 Tutorial. In this PyQt5 tutorial of Python, we will learn a Python binding of Qt, which is a cross-platform GUI toolkit.

Moreover, we will see how to plot various GUI elements like buttons, windows, and input dialogs.

We will talk about version PyQt5, which isn’t backwards-compatible with version PyQt4. Also, we will look at PyQt Applications.

Python PyQt5 Tutorial – Example and Applications

What is PyQt5?

PyQt is a Python binding of Qt, a cross-platform GUI toolkit.

This is a free software by Riverbank Computing and implements over 440 classes and more than 6000 functions and methods.

Some of these are-

PyQt5 Tutorial – What is PyQt5

1. Modules in PyQt5

We have the following modules available in PyQt5:

2. PyQt5 Installation

For this, you need to install PyQt5. You can use pip for this-

pip install pyqt5

To import it in the IDLE, you can do the following-

>>> import PyQt5

How to Create a Window in Python PyQt5?

Let’s take a simple example of PyQt5 in Python to create an empty window on our screen.

>>> import sys
>>> from PyQt5.QtWidgets import QApplication, QWidget
>>> app=QApplication(sys.argv)
>>> root=QWidget()
>>> root.resize(320,240)
>>> root.setWindowTitle('Hello, world!')
>>> root.show()

Output

Creating a Window in Python

To enter the mainloop for the application, we do the following-

sys.exit(app.exec_())

Another way to create a window will be:

>>> import sys
>>> from PyQt5.QtWidgets import QApplication, QWidget
>>> from PyQt5.QtGui import QIcon
>>> class App(QWidget):
      def __init__(self):
              super().__init__()
              self.title='Hello, world!'
              self.left=10
              self.top=10
              self.width=640
              self.height=480
              self.initUI()
      def initUI(self):
              self.setWindowTitle(self.title)
              self.setGeometry(self.left,self.top,self.width,self.height)
              self.show()
>>> if __name__=='__main__':
        app=QApplication(sys.argv)
        ex=App()
        sys.exit(app.exec_())

Output

Creating a Window in Python

Python PyQt5  – Adding a Status Bar

It is possible to add a status bar to our window.

>>> import sys
>>> from PyQt5.QtWidgets import QApplication,QWidget,QMainWindow #Imported one more module
>>> from PyQt5.QtGui import QIcon
>>> class App(QMainWindow):
       def __init__(self):
              super().__init__()
              self.title='Hello, world!'
              self.left=10
              self.top=10
              self.width=640
              self.height=480
              self.initUI()
def initUI(self):
              self.setWindowTitle(self.title)
              self.setGeometry(self.left,self.top,self.width,self.height)
              self.statusBar().showMessage('In progress') #Added
              self.show()
>>> if __name__=='__main__':
       app=QApplication(sys.argv)
       ex=App()

We add this to the main window and the showMessage() method prints it out to it.

Output

Adding a Status Bar in Python

PyQt5 Tutorial – Adding Buttons

Using the QPushButton class, we can add buttons to our screen.

>>> from PyQt5.QtWidgets import QApplication,QWidget,QPushButton
>>> from PyQt5.QtCore import pyqtSlot
>>> import sys
>>> class App(QWidget):
       def __init__(self):
               super().__init__()
               self.title='Hello, world!'
               self.left=10
               self.top=10
               self.width=640
               self.height=480
               self.initUI()
       def initUI(self):
               self.setWindowTitle(self.title)
               self.setGeometry(self.left,self.top,self.width,self.height)
               button=QPushButton('Click me',self)
               button.setToolTip('Thank you for thinking about me')
               button.move(100,70)
               self.show()
>>> if __name__=='__main__':
       app=QApplication(sys.argv)
       ex=App()

Output

Adding Buttons

PyQt5 Tutorial – Signals and Slots

On an event- like a user click- a PyQt5 widget can emit a signal. For a button click (a signal), we can specify an action (a slot).

>>> from PyQt5.QtWidgets import *
>>> import sys
>>> class Dialog(QDialog):
       def slot_method(self):
               print("Calling the slot")
       def __init__(self):
               super(Dialog,self).__init__()
               button=QPushButton("Click me")
               button.clicked.connect(self.slot_method)
               mainLayout=QVBoxLayout()
               mainLayout.addWidget(button)
               self.setLayout(mainLayout)
               self.setWindowTitle("Hello, world!")
>>> if __name__=='__main__':
       app=QApplication(sys.argv)
       dialog=Dialog()
>>> dialog.exec_()

Calling the slot

Signals and Slots

PyQt5 Tutorial – Message Boxes

Let’s ask the user if he likes cookies

>>> from PyQt5.QtWidgets import QApplication,QWidget,QPushButton,QMessageBox
>>> import sys
>>> from PyQt5.QtCore import pyqtSlot
>>> from PyQt5.QtGui import QIcon
>>> class App(QWidget):
       def __init__(self):
               super().__init__()
               self.title='Hello, world!'
               self.left=10
               self.top=10
               self.width=400
               self.height=250
               self.initUI()
       def initUI(self):
               self.setWindowTitle(self.title)
               self.setGeometry(self.left,self.top,self.width,self.height)
               buttonReply=QMessageBox.question(self, 'Hello', "Do you like cookies?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
               if buttonReply==QMessageBox.Yes:
                       print("Yeah")
               else: print("Nah")
               self.show()
>>> if __name__=='__main__':
       app=QApplication(sys.argv)
       ex=App()

Message Boxes

When we click yes, it prints Yeah, closes this message box and then opens a new window.

Message Boxes in Python

PyQt5 Tutorial – Adding a Textbox

For this, we use the methods setText() and text(); the widget is QLineEdit.

>>> from PyQt5.QtWidgets import QMainWindow,QApplication,QWidget,QPushButton,QAction,QLineEdit,QMessageBox
>>> import sys
>>> from PyQt5.QtGui import QIcon
>>> from PyQt5.QtCore import pyqtSlot
>>> class App(QMainWindow):
       def __init__(self):
               super().__init__()
               self.title='Hello, world!'
               self.left=10
               self.top=10
               self.width=400
               self.height=140
               self.initUI()
       def initUI(self):
               self.setWindowTitle(self.title)
               self.setGeometry(self.left,self.top,self.width,self.height)
               self.textbox=QLineEdit(self)
               self.textbox.move(30,30)
               self.textbox.resize(280,40)
               self.button=QPushButton('Click me',self)
               self.button.move(15,85)
               self.button.clicked.connect(self.on_click)
               self.show()
       @pyqtSlot()
       def on_click(self):
               textboxValue=self.textbox.text()
               QMessageBox.question(self, 'Hello, world!', "Confirm: "+textboxValue,                                                                            QMessageBox.Ok, QMessageBox.Ok)
               self.textbox.setText("...")
>>> if __name__=='__main__':
       app=QApplication(sys.argv)
       ex=App()

Output

Adding a Textbox

Adding a Textbox

PyQt5 Tutorial – Creating a Menu

Now let’s create a menu with headings

>>> import sys
>>> from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QPushButton, QAction
>>> from PyQt5.QtGui import QIcon
>>> from PyQt5.QtCore import pyqtSlot
>>> class App(QMainWindow):
       def __init__(self):
               super().__init__()
               self.title = 'Hello, world!’'
               self.left = 10
               self.top = 10
               self.width = 640
               self.height = 400
               self.initUI()
       def initUI(self):
               self.setWindowTitle(self.title)
               self.setGeometry(self.left,self.top,self.width,self.height)
               mainMenu=self.menuBar()
               fileMenu=mainMenu.addMenu('File')
               editMenu=mainMenu.addMenu('Edit')
               viewMenu=mainMenu.addMenu('View')
               searchMenu=mainMenu.addMenu('Search')
               toolsMenu=mainMenu.addMenu('Tools')
               helpMenu=mainMenu.addMenu('Help')
               exitButton=QAction(QIcon('exit24.png'), 'Exit', self)
               exitButton.setShortcut('Ctrl+Q')
               exitButton.setStatusTip('Exit application')
               exitButton.triggered.connect(self.close)
               fileMenu.addAction(exitButton)
               self.show()
>>> if __name__=='__main__':
       app=QApplication(sys.argv)
       ex=App()

Output

Creating a Menu

PyQt5 Tutorial – Setting Absolute Position

You can put your widgets anywhere you want on the screen.

>>> import sys
>>> from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QLabel
>>> from PyQt5.QtGui import QIcon
>>> class App(QMainWindow):
       def __init__(self):
               super().__init__()
               self.title = 'Hello, world!'
               self.left = 10
               self.top = 10
               self.width = 440
               self.height = 280
               self.initUI()
       def initUI(self):
               self.setWindowTitle(self.title)
               self.setGeometry(self.left, self.top, self.width, self.height)
               label = QLabel('Pink',self)
               label.move(50,50)
               label2 = QLabel('Blue',self)
               label2.move(100,100)
               label3 = QLabel('Green',self)
               label3.move(150,150)
               label4 = QLabel('Lavender',self)
               label4.move(200,200)
self.show()
>>> if __name__=='__main__':
       app=QApplication(sys.argv)
       ex=App()

Output

Setting Absolute Position

PyQt5 Tutorial – Creating Input Dialogs

It is possible to add an input dialog.

>>> import sys
>>> from PyQt5.QtWidgets import QApplication,QWidget,QInputDialog,QLineEdit
>>> from PyQt5.QtGui import QIcon
>>> class App(QWidget):
       def __init__(self):
               super().__init__()
               self.title='Hello, world!'
               self.left=10
               self.top=10
               self.width=300
               self.height=250
               self.initUI()
       def initUI(self):
               self.setWindowTitle(self.title)
               self.setGeometry(self.left,self.top,self.width,self.height)
               self.getDouble()
               self.show()
       def getDouble(self):
               d,okPressed=QInputDialog.getDouble(self,'Get double','Value',9,0.5,100,9.5)
               if okPressed:
                       print(d)
>>> if __name__=='__main__':
       app=QApplication(sys.argv)
       ex=App()

Output

Creating Input Dialogs

PyQt5 Tutorial – Loading Images

To load an image into your window, you can try the following-

>>> import sys
>>> from PyQt5.QtWidgets import QApplication,QWidget,QLabel
>>> from PyQt5.QtGui import QIcon,QPixmap
>>> import os
>>> os.chdir('C:\\Users\\Ram\\Desktop')
>>> class App(QWidget):
       def __init__(self):
               super().__init__()
               self.title='Hello, world!'
               self.left=10
               self.top=10
               self.width=640
               self.height=480
               self.initUI()
       def initUI(self):
               self.setWindowTitle(self.title)
               self.setGeometry(self.left,self.top,self.width,self.height)
               label=QLabel(self)
               pixmap=QPixmap('df.png')
               label.setPixmap(pixmap)
               self.resize(pixmap.width(),pixmap.height())
               self.show()
>>> if __name__=='__main__':
       app=QApplication(sys.argv)
       ex=App()

Output

Loading Images

PyQt5 Tutorial – Color Dialogs

A color dialog is one that will let you choose a color from a color picker.

>>> import sys
>>> from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QColorDialog
>>> from PyQt5.QtGui import QIcon
>>> from PyQt5.QtCore import pyqtSlot
>>> from PyQt5.QtGui import QColor
>>> class App(QWidget):
       def __init__(self):
              super().__init__()
              self.title='Hello, world!'
              self.left=10
              self.top=10
              self.width=320
              self.height=200
              self.initUI()
       def initUI(self):
              self.setWindowTitle(self.title)
              self.setGeometry(self.left,self.top,self.width,self.height)
              button=QPushButton('Open color dialog', self)
              button.setToolTip('This opens the color dialog')
              button.move(10,10)
              button.clicked.connect(self.on_click)
              self.show()
       @pyqtSlot()
       def on_click(self):
              openColorDialog(self)
>>> def openColorDialog(self):
       color=QColorDialog.getColor()
       if color.isValid():
              print(color.name())
>>> if __name__=='__main__':
       app=QApplication(sys.argv)
       ex=App()

Output

Color Dialogs

Color Dialogs

And then when we pick a color and click on ‘OK’, it gives us the HTML code of that color.

Color Dialogs

PyQt5 Tutorial – Font Dialogs

Now to choose a font-

>>> import sys
>>> from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QFontDialog
>>> from PyQt5.QtGui import QIcon
>>> from PyQt5.QtCore import pyqtSlot
>>> class App(QWidget):
       def __init__(self):
               super().__init__()
               self.title='Hello, world!'
               self.left=10
               self.top=10
               self.width=320
               self.height=200
               self.initUI()
       def initUI(self):
               self.setWindowTitle(self.title)
               self.setGeometry(self.left,self.top,self.width,self.height)
               button=QPushButton('The font dialog', self)
               button.setToolTip('Opens the font dialog')
               button.move(50,50)
               button.clicked.connect(self.on_click)
               self.show()
       @pyqtSlot()
       def on_click(self):
               print('Click')
               openFontDialog(self)
>>> def openFontDialog(self):
       font,ok=QFontDialog.getFont()
       if ok:
print(font.toString())
>>> if __name__=='__main__':
       app=QApplication(sys.argv)
       ex=App()

Output

PyQt5 Tutorial – Font Dialogs

 Font Dialogs

Font Dialogs

Python PyQt Applications

Here’s a list of applications that make use of PyQt-

So, this was all about PyQt5 Tutorial. Hope you like our explanation.

Python Interview Questions on PyQt5

  1. What is PyQt5 in Python?
  2. What is PyQt5 used for in Python?
  3. What is the difference between PyQt4 and PyQt5?
  4. How to run PyQt5 on Windows?
  5. What are the benefits of using PyQt5 in Python?

Conclusion

Hence, in this Python PyQt5 Tutorial, we saw how to create GUI elements with PyQt5. Once you get the syntax, it seems easy to work with PyQt5. 

Exit mobile version