当我在终端中使用功能time.sleep()时,这没问题。当我使用PyQt并想使用标签时,它会崩溃和/或仅显示最后一个数字。
顺便说一句:我想要一个功能,例如2020年至2030年的一年以各种速度变化,用户可以更改,并且年份应显示在标签中。
非常感谢您的帮助。
# timer that counts in the future with various speed // still crashing
def timer(self):
x=datetime.datetime.now()
z=x.ctime()
self.ui.labelDateTime.setText(z)
var=x.year
while True:
if var==2030:
break
else:
var+=1
y=x.replace(year=var)
z=y.ctime()
self.ui.labelDateTime.setText(z)
time.sleep(0.5)
print("You are dead")
您应该在for循环中调用QtCore.QCoreApplication.processEvents()
,以使Qt的事件循环处理传入事件(通过键盘,鼠标或睡眠)。
尽管调用QtCore.QCoreApplication.processEvents()
可行,但我在网络上的许多地方都读到它应该是最后的选择。不幸的是,没有消息来源清楚地解释了原因-但例如参见
所以它似乎确实允许,但总的来说,使用QTimer
或QThread
似乎是更好的设计。