我有一个“预处理”功能,可能需要花费一些时间才能执行。因此,我希望它与我的UI同时运行。我尝试使用QThread进行此操作:
class Preprocessor(QThread):
done = pyqtSignal(ndarray)
def __init__(self, image):
super(Preprocessor, self).__init__()
self.image = image
def run(self) -> None:
result = preprocess(self.image)
self.done.emit(result)
然后运行:
preprocessor = Preprocessor(image)
preprocessor.start()
preprocessor.done.connect(self.handler_function)
但是现在当我按下UI中的按钮时,它仍然只运行我的预处理程序并阻止UI响应。我无法更改有关预处理程序代码的任何内容。
尝试:
import sys
from PyQt5.Qt import *
class Preprocessor(QThread):
done = pyqtSignal(object) # ndarray
def __init__(self, image):
super(Preprocessor, self).__init__()
self.image = image
def run(self) -> None:
result = self.preprocess(self.image)
self.done.emit(result)
def preprocess(self, image):
while image:
self.done.emit(image) #(result)
image -= 1
self.msleep(100)
return "The End"
class ExampleApp(QMainWindow):
def __init__(self):
super().__init__()
image = 100
self.preprocessor = Preprocessor(image) # self. +++
self.preprocessor.done.connect(self.handler_function) # +
self.preprocessor.start() #
# preprocessor.done.connect(self.handler_function)
def handler_function(self, obj):
print(obj)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = ExampleApp()
window.show()
app.exec_()