Open In App

How to use threading in PyQt5?

Prerequisite: PyQt5 and multithreading

Multithreading refers to concurrently executing multiple threads by rapidly switching the control of the CPU between threads (called context switching). The Python Global Interpreter Lock limits one thread to run at a time even if the machine contains multiple processors.​



In this article, we will learn, how to use threading in Pyqt5. While Creating a GUI there will be a need to do multiple work/operations at the backend. Suppose we want to perform 4 operations simultaneously. The problem here is, each operation executes one by one. During the execution of one operation, the GUI window will also not move and this is why we need threading. Both implementations are given below which obviously will help understand their differences better.

Approach



Without Threading

Working without threads, makes the process delayed. Also, the window will not move until full execution takes place.




# Import Module
import sys
from PyQt5.QtWidgets import *
import time
  
class ListBox(QWidget):
  
    def __init__(self):
        super().__init__()
  
        self.Button()
  
    def Button(self):
        # Add Push Button
        clear_btn = QPushButton('Click Me', self)
        clear_btn.clicked.connect(self.Operation)
  
        # Set geometry
        self.setGeometry(200, 200, 200, 200)
  
        # Display QlistWidget
        self.show()
  
    def Operation(self):
        print("time start")
        time.sleep(10)
        print("time stop")
  
  
if __name__ == '__main__':
    app = QApplication(sys.argv)
      
    # Call ListBox Class
    ex = ListBox()
  
    # Close the window
    sys.exit(app.exec_())

Output:

With Threading

Whenever we click on the “Click Me” Button, it will call the thread() method. Inside the thread method, we are creating a Thread Object where we define our function name.




# Import Module
import sys
from PyQt5.QtWidgets import *
import time
from threading import *
  
class ListBox(QWidget):
  
    def __init__(self):
        super().__init__()
  
        self.Button()
  
    def Button(self):
        # Add Push Button
        clear_btn = QPushButton('Click Me', self)
        clear_btn.clicked.connect(self.thread)
  
        # Set geometry
        self.setGeometry(200, 200, 200, 200)
  
        # Display QlistWidget
        self.show()
  
    def thread(self):
        t1=Thread(target=self.Operation)
        t1.start()
  
    def Operation(self):
        print("time start")
        time.sleep(10)
        print("time stop")
  
  
if __name__ == '__main__':
    app = QApplication(sys.argv)
      
    # Call ListBox Class
    ex = ListBox()
  
    # Close the window
    sys.exit(app.exec_())

Output:


Article Tags :