Demo for using threads in PYQT

Case description

pyqt creates a thread and executes a function named Meth1. The function has two parameters a and b. The value of a+b is calculated in the function, and then the text of the button btn is changed to the function return value.

Case analysis

In PyQt, UI elements cannot be accessed directly across threads. This is due to Qt's threading model and the special nature of GUI threads. However, you can update the UI in the main thread through the signals and slots mechanism.

Code

Here is a simple example that demonstrates how to create a new thread to run the Meth1 function and then send the results to the main thread's slot to update the button's text.

from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton

# 定义你的函数
def Meth1(a, b):
    return a + b

class Worker(QThread):
    resultReady = pyqtSignal(int)  # 创建一个信号,用于传递结果

    def run(self):
        result = Meth1(5, 10)
        self.resultReady.emit(result)  # 发出信号

class Window(QMainWindow):
    def __init__(self):
        super().__init__()

        self.btn = QPushButton('Button')
        self.setCentralWidget(self.btn)

        self.worker = Worker(self)
        self.worker.resultReady.connect(self.on_result_ready)
        self.worker.start()

    def on_result_ready(self, result):
        self.btn.setText(str(result))  # 将按钮的文本设置为函数返回值

if __name__ == '__main__':
    app = QApplication([])
    window = Window()
    window.show()
    app.exec_()

Guess you like

Origin blog.csdn.net/qq_41704436/article/details/132672700