【问题标题】:Single shot time not working inside pyqt4 QThread单次拍摄时间在pyqt4 QThread中不起作用
【发布时间】:2018-05-01 05:13:51
【问题描述】:

我正在尝试在 QThread 中使用单次计时器,但它不起作用。以下是我正在使用的代码:

class thread1((QtCore.QThread):
    def __init__(self,parent):
        QtCore.QThread.__init__(self, parent)
        self.Timer1 = None

    def __del__(self):
        self.wait()

    def timerPINNo(self):
        print "Timer completed"

    def run(self):
        tempVal0 = getData()
        if tempVal0 == 0:
            self.Timer1 = QtCore.QTimer()
            self.Timer1.timeout.connect(self.timerPINNo)
            self.Timer1.setSingleShot(True)
            self.Timer1.start(5000)
        else: pass

我面临的问题是,超时后 timerPINNo 函数永远不会被调用。单发在正常使用时有效,但在我从 QThread 调用时无效。我在哪里犯错了?

【问题讨论】:

    标签: python python-2.7 pyqt pyqt4 qthread


    【解决方案1】:

    这个问题是因为如果 run 方法完成执行线程完成它的执行,因此它被消除,因此计时器也被消除。解决方法是让run方法一直运行,必须使用QEventLoop

    import sys
    from PyQt4 import QtCore
    
    class thread1(QtCore.QThread):
        def __init__(self,*args, **kwargs):
            QtCore.QThread.__init__(self, *args, **kwargs)
            self.Timer1 = None
    
        def __del__(self):
            self.wait()
    
        def timerPINNo(self):
            print("Timer completed")
    
    
        def run(self):
            tempVal0 = getData()
            if tempVal0 == 0:
                self.Timer1 = QtCore.QTimer()
                self.Timer1.timeout.connect(self.timerPINNo)
                self.Timer1.setSingleShot(True)
                self.Timer1.start(5000)
                loop = QtCore.QEventLoop()
                loop.exec_()
    
    if __name__ == "__main__":
       app = QtCore.QCoreApplication(sys.argv)
       th = thread1()
       th.start()
       sys.exit(app.exec_())
    

    【讨论】:

    • 更好的解决方案是根本不覆盖run 方法,这样您就不会阻止QThread 的内置事件循环运行。
    • 你能给我解释一下吗
    猜你喜欢
    • 2021-05-31
    • 2013-03-20
    • 2017-05-17
    • 2012-12-18
    • 1970-01-01
    • 1970-01-01
    • 2011-08-05
    • 2019-01-21
    • 1970-01-01
    相关资源
    最近更新 更多