QThread/信号逻辑

2024-09-30 14:29:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我在写一个论坛的通知。我尝试使用带有QTimer的QThread来定期检查新回复。但是,我的线程中的check()函数不在线程中运行,它阻塞了GUI。你能说说这有什么不对吗?在

我怀疑信号,我使用QTimer的超时信号来运行check方法,但是创建和连接超时信号来检查函数是在run方法之外的。但是当我在run方法中移动self.timer=QTimer(); timer.timeout.connect(self.check)时,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代码中启动线程的方法:

^{pr2}$

Tags: 方法runselftimedefcheckloginpassword
1条回答
网友
1楼 · 发布于 2024-09-30 14:29:54

{看来问题出在你身上。我看不出时间是在哪里定义的,但是如果这是python的正常时间模块,它会使python解释器暂停,我想这就是问题的原因。在

因为您不想混合使用python线程和qt线程,所以我建议您使用QThread.wait()。它应该使一切变得简单:

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

相关问题 更多 >