2013-07-10 34 views
0

我在Python3中使用PyQt。QT定時器不能調用函數

我的QTimer s沒有調用它們被告知要連接的功能。 isActive()正在返回True,而​​正在正常工作。下面的代碼(獨立工作)演示了這個問題:該線程已成功啓動,但從不調用該函數。大部分代碼是樣板PyQT。據我所知,我按照文檔使用這個。它在一個帶有事件循環的線程中。有任何想法嗎?

import sys 
from PyQt5 import QtCore, QtWidgets 

class Thread(QtCore.QThread): 
    def __init__(self): 
     QtCore.QThread.__init__(self) 

    def run(self): 
     thread_func() 


def thread_func(): 
    print("Thread works") 
    timer = QtCore.QTimer() 
    timer.timeout.connect(timer_func) 
    timer.start(1000) 
    print(timer.remainingTime()) 
    print(timer.isActive()) 

def timer_func(): 
    print("Timer works") 

app = QtWidgets.QApplication(sys.argv) 
thread_instance = Thread() 
thread_instance.start() 
thread_instance.exec_() 
sys.exit(app.exec_()) 

回答

3

你打電話從withn你的線程的run方法thread_func,這意味着你的計時器在創建該函數住在該線程的事件循環。要啓動線程事件循環,您必須將其稱爲exec_()方法from within it's run method,而不是來自主thrad。在你的例子中,app.exec_()永遠不會被執行。爲了使其工作,只需將exec_呼叫移動到線程的run

另一個問題是,當thread_func完成時,你的計時器被破壞。爲了保持它的活力,你必須在某處保留一個引用。

import sys 
from PyQt5 import QtCore, QtWidgets 

class Thread(QtCore.QThread): 
    def __init__(self): 
     QtCore.QThread.__init__(self) 

    def run(self): 
     thread_func() 
     self.exec_() 

timers = [] 

def thread_func(): 
    print("Thread works") 
    timer = QtCore.QTimer() 
    timer.timeout.connect(timer_func) 
    timer.start(1000) 
    print(timer.remainingTime()) 
    print(timer.isActive()) 
    timers.append(timer) 

def timer_func(): 
    print("Timer works") 

app = QtWidgets.QApplication(sys.argv) 
thread_instance = Thread() 
thread_instance.start() 
sys.exit(app.exec_()) 
+0

非常感謝!這解決了這個問題。也幫助我理解QT代碼的結構總體上好一點。 –