python - 更新 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”。
解决方案
推荐阅读
- c++ - 如何通过其不同的属性对对象的类(不是结构)进行排序?
- visual-studio - 为什么 Microsoft Visual Studio 2019 会自动关闭?
- javascript - 如何在 Express.js 中向客户端发送响应之后/时重定向到某个路由?
- javascript - 如何在 TestCafe 中测试网络摄像头功能?
- python - 我在 python 中遇到 OpenCV 错误...我的代码如下所示?请尽快解决。提前致谢
- java - 由于线程异常导致 Hive 内存不足
- javascript - 在 Firefox 中使用 css“变换”和“透视”重复 2 层 css 视差背景(背景未在内容高度切断)
- content-security-policy - CSP frame-src 指令的 Facebook 聊天插件问题
- google-cloud-firestore - firestore 文档中的“client”是什么意思
- node.js - 如何将命令行参数传递给角度应用程序