【问题标题】:PyQt5 QTimer in QThread is being "garbage collected"?QThread 中的 PyQt5 QTimer 正在“垃圾收集”?
【发布时间】:2018-06-27 20:26:15
【问题描述】:

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

【问题讨论】:

    标签: python pyqt pyqt5 qthread qtimer


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-21
      • 1970-01-01
      • 1970-01-01
      • 2018-12-30
      • 1970-01-01
      • 2011-02-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多