繁体   English   中英

QThread 中的 PyQt5 QTimer 正在被“垃圾收集”?

[英]PyQt5 QTimer in QThread is being “garbage collected”?

我正在尝试在 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_())

虽然@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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM