PyQt is a set of Python bindings for the Qt application framework and runs on all platforms supported by Qt including Windows, macOS, Linux, iOS, Android, and embedded systems. In this tutorial, we will delve into how to execute tasks in a separate thread using PyQt.
When designing PyQt applications, it is important to delegate heavy tasks that may block the main thread, such as network operations or computations, to separate threads to keep the user interface responsive. This is crucial for creating a smooth user experience and preventing the application from freezing.
To achieve this, we will create a PyQt application with a simple user interface and a button that triggers a long-running task. We will execute this task in a separate thread to illustrate how to maintain the responsiveness of the GUI.
First, make sure you have PyQt installed. You can install PyQt using pip:
pip install pyqt5
Next, create a new Python file and import the necessary modules:
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget
from PyQt5.QtCore import QThread, pyqtSignal
Now, let’s define a custom worker class that will perform the long-running task in a separate thread. We will emit a signal to communicate with the main thread when the task is complete.
class Worker(QThread):
finished = pyqtSignal()
def run(self):
# Perform a long-running task here
self.finished.emit()
Next, we will create the main application window and connect the button to trigger the long-running task:
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("PyQt Separate Thread Example")
self.resize(400, 300)
layout = QVBoxLayout()
self.button = QPushButton("Start Task", self)
self.button.clicked.connect(self.start_task)
layout.addWidget(self.button)
widget = QWidget()
widget.setLayout(layout)
self.setCentralWidget(widget)
def start_task(self):
self.worker = Worker()
self.worker.finished.connect(self.on_task_finished)
self.worker.start()
def on_task_finished(self):
print("Task completed")
Finally, we create a QApplication instance and run the main event loop:
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
Now, when you run the application, clicking the "Start Task" button will trigger the execution of the long-running task in a separate thread. You can perform any heavy computation or network operations within the run
method of the Worker
class. Remember to use signals to communicate between the separate thread and the main thread.
By following this tutorial, you have learned how to execute tasks in a separate thread using PyQt. This will help you create responsive GUI applications that provide a smooth user experience. Experiment with different tasks and thread communication mechanisms to further enhance your PyQt applications.
Спасибо. Отличные видео про QT. B всё очень понятно.