QThread中的PyQt5 QTimer被"垃圾收集"?

时间:2018-01-18 17:10:52

标签: python pyqt pyqt5 qthread qtimer

我试图在QThread中使用QTimer,但它没有调用我需要它调用的函数。我读了一些关于垃圾收集的事情,并且计时器在它有机会被使用之前被抛出(根据我的理解)。我尝试了其他代码示例中的许多方法,但我误解了一些内容,因为这些示例没有帮助。

run_()方法由Main_Window类中的按钮触发。 将计时器的实例化移动到run()方法没有帮助。 这有什么问题?

#Main_Window class is here

class TheThread(QThread):

    def __init__(self, Main_Window):
        QThread.__init__(self)

        #some code above
        self.timeTaken = 0
        self.myTimer = QTimer()
        self.myTimer.timeout.connect(self.track_time)

    def track_time(self):
        #Not being called
        self.timeTaken += 0.1

    def run(self):
        #some code above
        self.myTimer.start(1000)
        #code in a while loop below

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = Main_Window()
    sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:0)

虽然@ eyllanesc的答案有效,但run方法已经包含一个事件循环(只要你不覆盖它!)。所以你可以这样做:

class TheThread(QtCore.QThread):
    def __init__(self, Main_Window):
        QtCore.QThread.__init__(self)
        #some code above
        self.timeTaken = 0
        self.myTimer = QtCore.QTimer()
        self.myTimer.moveToThread(self)
        self.myTimer.timeout.connect(self.track_time)
        # once the thread starts, the started signal is emitted
        self.started.connect(self.start_timer)
        # start the thread, which will emit the above signal!
        self.start()

    def start_timer(self):
        self.myTimer.start(1000)

    def track_time(self):
        self.timeTaken += 0.1
        print(self.timeTaken)