首页 > 解决方案 > 更新 UI 的 PyQt5 线程

问题描述

我正在尝试制作一个简单的天气应用程序,它还显示当前时间。但是,经过多次反复试验,我正在寻求帮助。我得出的结论是,我必须致力于在我的 PyQt UI 的后台持续运行时钟的线程。虽然,它只是冻结和崩溃,我不明白为什么。如您所知,我已经检查了有关此问题的多个帖子,例如[1][2]。但我一点也不聪明...

这是最小的可重现代码:


class Clock(QObject):
    updated_time = pyqtSignal()
    
    def __init__(self, parent=None):
        QObject.__init__(self,parent=parent)

    def get_time(self):
        #This code is meant to be run continously
        #For troubleshooting, ive removed the while-loop momentarily

        QThread.sleep(1)
        now = datetime.now()
        current_time = now.strftime("%H:%M")
        self.updated_time.emit()

class MainWindow(QMainWindow):
    
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.initUI()


    def initUI(self):
        self.setWindowTitle('WeatherApp')
        self.resize(700, 500)
        self.clock_label = QLabel(self)
        self.clock_label.setText('make me change')

        self.show()

        
        thread = QThread()
        worker = Clock()
        worker.moveToThread(thread)
        thread.started.connect(lambda: worker.get_time())
        worker.updated_time.connect(self.update_clock())

        thread.start()  
        
    def update_clock(self):
        self.clock_label.setText(current_time)

def main():

    app = QApplication(sys.argv)
    mw = MainWindow()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

当前代码使用最初声明的变量current_time的值创建带有时钟标签的窗口。在后台,来自 worker (do_work) 的函数在后台运行,以 1 秒的延迟连续迭代。正如我从帖子1中了解的那样,我不应该从线程更新 UI,但即使使用 invokeMethod 我也无法取得任何成功。问题不应该像从函数 do_work 发出信号那样简单吗?应用程序?我添加了一个,但收到错误消息:“AttributeError: 'QThread' object has no attribute”。

标签: pythonmultithreadingpyqt5signals

解决方案


推荐阅读