QThread/Signal Logic
I'm trying to write a notifier for a forum. I'm trying to use a QThread with a QTimer for checking for new replies periodically. But, my check() function in my thread don't run in thread, it blocks the GUI. Can you say what is wrong with that?
I am suspecting of signals, I'm using the QTimer's timeout signal for running check
method, but creating and connecting timeout signal to check function is outside of run
method. But when I move self.timer=QTimer(); timer.timeout.connect(self.check)
inside run
method, self.check
never triggered. Anyway, can you tell me where am I wrong?
class Worker(QtCore.QThread):
check_started = QtCore.pyqtSignal()
check_successful = QtCore.pyqtSignal()
check_failed = QtCore.pyqtSignal()
def __init__(self, user="", password="", check_frequency=5):
QtCore.QThread.__init__(self)
self.login_info = {"user": user, "password": password}
self.check_frequency = check_frequency
self.last_check_time = 0
self.timer = QtCore.QTimer()
self.timer.timeout.connect(self.check) #Would it run in thread or not?
self.unreads = {}
def run(self):
#When I do timer initialization here, it never triggers
self.check()
self.timer.start(self.check_frequency * 1000 * 60)
def check(self):
print "checking"
self.last_check_time = time.time()
self.check_started.emit()
check_result = self.check_f开发者_C百科or_unreads()
if check_result:
self.check_successful.emit()
else:
self.check_failed.emit()
def check_for_unreads(self):
frm = Forum(self.login_info["user"], self.login_info["password"])
#This class just uses Mechanize to fetch some pages;
#Not calculation or CPU-intensive actions.
if frm.login(): #returns true if successful login, else false
frm.get_unread_replies()
self.unreads=frm.unreads
return True
else:
return False
Sorry for kind of multiple questions. I will try to explain more if something is unclear.
Edit: This is how I start thread in my gui code:
self.checker = Worker()
self.checker.login_info["user"] = self.settings["user"]
self.checker.login_info["password"] = self.settings["password"]
self.checker.check_frequency = self.settings["time"]
self.checker.check_started.connect(self.check_started)
self.checker.check_successful.connect(self.check_successful)
self.checker.check_failed.connect(self.check_failed)
self.checker.start()
It looks like the main problem is that you're calling time.sleep(). I don't see where time is defined, but if that's the normal time module for python that will make the python interpreter pause which I expect is the cause of the problem.
Since you don't want to mix python threads and qt threads, I'd recommend that you use QThread.wait(). It should make everything much simpler:
def run(self):
while True:
self.check()
self.wait(self.check_frequency) # or do necessary unit conversion
精彩评论