qt线程池子线程辅助类传信号

发布时间:2023年12月22日
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton
from PyQt5.QtCore import QObject, QRunnable, pyqtSignal, QThreadPool

# 辅助类,用于定义信号
class WorkerSignals(QObject):
    print('pass signal')
    finished = pyqtSignal(bool)  # 发射布尔值的信号

# 工作线程类
class Worker(QRunnable):
    def __init__(self):
        super(Worker, self).__init__()
        self.signals = WorkerSignals()

    def run(self):
        # 这里执行一些工作
        print('Worker thread is running...')
        # 模拟长时间运行的任务
        import time
        time.sleep(5)
        # 工作完成后发射信号

        self.signals.finished.emit(False)

# 主窗口类
class MainApp(QMainWindow):
    def __init__(self):
        super(MainApp, self).__init__()
        self.setWindowTitle('PyQt5 Signal Slot Example')
        self.initUI()
        self.threadpool = QThreadPool()

    def initUI(self):
        button = QPushButton('Start Thread', self)
        button.clicked.connect(self.start_thread)
        self.setFixedSize(200, 100)
        button.resize(200, 40)

    def start_thread(self):
        worker = Worker()
        worker.signals.finished.connect(self.on_finished)
        self.threadpool.start(worker)

    def on_finished(self, result):
        print(f'Worker thread finished with result: {result}')

# 应用程序入口点
def main():
    app = QApplication(sys.argv)
    main_app = MainApp()
    main_app.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

文章来源:https://blog.csdn.net/tenc1239/article/details/135161154
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。