如何知道QThread是否正确退出或终止?

时间:2018-11-23 13:18:35

标签: qt qthread qt-signals

我在Qt 4.8中发现终止信号,如您在此处看到的: http://doc.qt.io/archives/qt-4.8/qthread.html#terminated

但是现在在Qt 5.8中没有这样的事情。 http://doc.qt.io/archives/qt-5.8/qthread.html

即使线程已完成,即使线程已终止,似乎也会发出完成信号。但是,有没有办法知道QThread是否正确退出或终止了?

1 个答案:

答案 0 :(得分:0)

我使用了@Scheff提出的以下模式

class MyQThread(QThread):
    def __init__(self):
        self.__terminated = None
        super().__init__()

    def wasTerminated(self):
        if self.__terminated is None:
            return True
        return False

    def run(self):
        # Add at end of run
        self.__terminated = False

并在呼叫者中关注

class Worker(QObject):
    def __init__(self):
        super().__init__()
        self.thread = MyQThread()
        self.thread.finished.connect(self.finishedSlot)

    def finishedSlot(self):
        if self.thread.wasTerminated():
            print("Thread was killed before finished")
        else:
            print("Thread results are ok")