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()