所以我尝试创建一个计时器或排序,启动按钮启动计时器,我需要用停止按钮停止计时器,然后记录时间。。。我似乎不知道如何停止计时器函数一旦启动。我尝试过if语句、disconnect()和许多其他语句。。。 我意识到qt中已经有一个计时器了,但我正试图用这种方式来解决它。谢谢。在
import sys
import time
from PyQt4 import QtCore, QtGui, uic
form_class = uic.loadUiType("/Users/Home/Desktop/Timer/timer.ui")[0]
class MyWindowClass(QtGui.QMainWindow, form_class):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.setupUi(self)
self.startButton.clicked.connect(self.timer)
def timer(self):
timeL = 0
self.stopButton.clicked.connect(False)
while True:
self.timeView.display(timeL)
timeL = timeL + 1
time.sleep(1)
app.processEvents()
app = QtGui.QApplication(sys.argv)
myWindow = MyWindowClass(None)
myWindow.show()
app.exec_()
使用标志控制循环。然后重置连接到停止按钮的插槽中的标志:
^{pr2}$QTimer
更好,因为在更新ui时没有延迟。但您可以通过使用内部循环更频繁地调用processEvents
来改进示例:你在找}。在
QElapsedTimer
,而不是{操作系统已经在为您测量时间的流逝。你自己干得再好不过了。在
“我正试着用这种方法来计算”——它比使用
QElapsedTimer
更不准确,因为你假设已经过了你想睡觉的时间。这几乎永远不会是真的:实际经过的时间量与sleep
的参数不同。更糟糕的是,这些错误通常也是系统性的,所以你的时间积累会有偏差,随着时间的推移,你的时间积累会变得不那么准确。所以,别这么做。这没道理。也许你没有告诉我们你到底想做什么:如果你问的是一个不起作用的特定解决方案,那么告诉我们该解决方案应该针对什么问题。为什么你想用这种方式来解决这个问题?在从概念上讲,Qt中有三种不同的计时器:
{1}它是一个计时系统的计时通道。您应该使用这个类来测量按钮单击之间经过了多少时间。
QTime
就像一个挂钟:你可以问它通过currentTime()
的时间,然后取两个时间读数之间的差值来获得经过的时间。只有当您需要知道绝对时间时才使用这个类,否则QElapsedTimer
将为经过的时间度量提供更好的分辨率。QTimer
是超时的来源:它是一种定期调用代码的方法。这并不是用来测量时间的,只是为了让代码周期性地运行,例如,当您希望刷新屏幕显示或实现周期性地发出哔声的节拍器时。不能保证您的代码会被及时调用,也不能保证不会错过一些节拍。你想保证它,你需要写一个内核驱动程序,没有办法。下面是python3.5中使用PyQt4的完整示例。它使用
QElapsedTimer
来测量按钮按下之间的时间间隔,使用QTimer
来保持时间显示的刷新。在听起来你想在QThread上使用QTimer。 这个答案会给你你所需要的一切。 https://stackoverflow.com/a/18960953/5757280
相关问题 更多 >
编程相关推荐