QThread /信号逻辑

时间:2011-06-24 14:10:07

标签: python pyqt

我正在尝试为论坛编写通知程序。我正在尝试使用带有QTimer的QThread来定期检查新的回复。但是,我的线程中的check()函数不在线程中运行,它会阻止GUI。你能说出来有什么问题吗?

我怀疑有信号,我正在使用QTimer的超时信号来运行check方法,但创建并连接超时信号以检查功能是在run方法之外。但是当我在self.timer=QTimer(); timer.timeout.connect(self.check)方法中移动run时,self.check从未触发过。无论如何,你能告诉我我错在哪里吗?

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_for_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

很抱歉有多个问题。如果不清楚,我会尝试解释更多。

编辑:这是我在gui代码中启动线程的方式:

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()

1 个答案:

答案 0 :(得分:0)

看起来主要的问题是你正在呼叫time.sleep()。我没有看到时间定义的地方,但是如果这是python的正常时间模块,它将使python解释器暂停,我期望这是问题的原因。

由于你不想混合python线程和qt线程,我建议你使用QThread.wait()。它应该使一切变得更加简单:

def run(self):
    while True:
        self.check()
        self.wait(self.check_frequency) # or do necessary unit conversion