在QTimer Singleshot后终止QThread

问题描述 投票:0回答:1

我有一个问题。我正在运行一个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返回主功能。

python python-3.x pyqt pyqt5
1个回答
0
投票

不需要计时器。使用线程的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()
© www.soinside.com 2019 - 2024. All rights reserved.