我遇到了一个问题。我正在运行一个PyQt5表单,该表单运行一个名为Task()
的工作程序(我不会深入了解其代码的细节,但它基本上只是将一个值返回到QLabel
),就像这样在QThread中:
class Menu(QMainWindow):
def __init__(self, workers):
super().__init__()
self.central_widget = QWidget()
self.setCentralWidget(self.central_widget)
lay = QVBoxLayout(self.central_widget)
self.setFixedSize(500, 350)
Pic = QLabel(self)
self.Total = QLabel("Total: <font color='orange'>%s</font>" % (to_check()), alignment=QtCore.Qt.AlignHCenter)
lay.addWidget(self.Total)
thread = QtCore.QThread(self)
thread.start()
self.worker = Task()
self.worker.moveToThread(thread)
self.worker.totalChanged.connect(self.updateTotal)
QtCore.QTimer.singleShot(0, self.worker.dostuff)
thread.finished.connect(self.terminate)
@QtCore.pyqtSlot(int)
def updateTotal(self, total):
self.Total.setText("Total: <font color='orange'>%s</font>" % (total))
def terminate(self):
print("FINISHED")
self.worker.quit()
self.worker.wait()
self.close()
我想要的是程序在terminate
函数完成后调用Task().dostuff()
插槽(并基本上终止线程和函数)-但我似乎做不到工作。
我不确定如何通过QTimer.singleshot
返回到主要功能。
答案 0 :(得分:1)
不需要计时器。使用线程的started
信号启动工作程序,并向工作程序类添加finished
信号以退出线程:
class Task(QtCore.QObject):
totalChanged = QtCore.pyqtSignal(int)
finished = QtCore.pyqtSignal()
def dostuff(self):
# do stuff ...
self.finished.emit()
class Menu(QtWidgets.QMainWindow):
def __init__(self, workers):
super().__init__()
...
self.thread = QtCore.QThread()
self.worker = Task()
self.worker.moveToThread(self.thread)
self.worker.totalChanged.connect(self.updateTotal)
self.worker.finished.connect(self.thread.quit)
self.thread.started.connect(self.worker.dostuff)
self.thread.start()