81 lines
2.7 KiB
Python
81 lines
2.7 KiB
Python
import sys, traceback
|
||
from PyQt5.QtCore import QRunnable, QObject, pyqtSignal, pyqtSlot
|
||
|
||
class WorkerSignals(QObject):
|
||
'''
|
||
Defines the signals available from a running worker thread.
|
||
|
||
Supported signals are:
|
||
|
||
finished
|
||
No data
|
||
|
||
error
|
||
`tuple` (exctype, value, traceback.format_exc() )
|
||
|
||
result
|
||
`object` data returned from processing, anything
|
||
|
||
progress
|
||
`int` indicating % progress
|
||
|
||
# 信号必须定义为类属性,不能放在__init__方法里
|
||
'''
|
||
finished = pyqtSignal()
|
||
error = pyqtSignal(tuple)
|
||
result = pyqtSignal(object)
|
||
progress = pyqtSignal(int) # 可以用作进度条
|
||
|
||
serial = pyqtSignal(object) # 2record_system_v26的此信号移动到类SerialPort中了
|
||
|
||
image_signal = pyqtSignal(dict) # 只用在2record_system_v25中
|
||
spectral_signal = pyqtSignal(dict) # 只用在2record_system_v25中
|
||
|
||
openinfo = pyqtSignal(int) # 只用在2record_system_v25中
|
||
plotsignal = pyqtSignal() # 2record_system_v26的此信号移动到类ImageWindowPhone中了
|
||
|
||
# https://www.learnpyqt.com/courses/concurrent-execution/multithreading-pyqt-applications-qthreadpool/
|
||
# 用于qt多线程:运行long-time task
|
||
class Worker(QRunnable):
|
||
'''
|
||
Worker thread
|
||
|
||
Inherits from QRunnable to handler worker thread setup, signals and wrap-up.
|
||
|
||
:param callback: The function callback to run on this worker thread. Supplied args and
|
||
kwargs will be passed through to the runner.
|
||
:type callback: function
|
||
:param args: Arguments to pass to the callback function
|
||
:param kwargs: Keywords to pass to the callback function
|
||
|
||
'''
|
||
|
||
def __init__(self, fn, *args, **kwargs):
|
||
super(Worker, self).__init__()
|
||
|
||
# Store constructor arguments (re-used for processing)
|
||
self.fn = fn
|
||
self.args = args
|
||
self.kwargs = kwargs
|
||
self.signals = WorkerSignals()
|
||
|
||
# Add the callback to our kwargs
|
||
# self.kwargs['progress_callback'] = self.signals.progress
|
||
|
||
@pyqtSlot()
|
||
def run(self):
|
||
'''
|
||
Initialise the runner function with passed args, kwargs.
|
||
'''
|
||
try: # 如果有错,就捕捉错误
|
||
result = self.fn(*self.args, **self.kwargs)
|
||
except Exception: # 根据错误进行处理
|
||
traceback.print_exc()
|
||
exctype, value = sys.exc_info()[:2]
|
||
|
||
self.signals.error.emit((exctype, value, traceback.format_exc()))
|
||
else: # 如果没有错误执行下面代码
|
||
self.signals.finished.emit() # Done
|
||
self.signals.result.emit(result) # Return the result of the processing
|
||
finally: # 不管有错无错,都要执行下面代码
|
||
pass |