计时器

QObject 是所有 Qt 对象的基类,在 Qt 中提供基本计时器支持。采用 QObject::startTimer (),启动计时器以毫秒为单位的间隔作为自变量。函数返回唯一整数计时器 ID。计时器现在将按定期间隔被激发,直到明确调用 QObject::killTimer () 采用计时器 ID。

要使此机制工作,应用程序必须在事件循环中运行。启动事件循环采用 QApplication::exec ()。当计时器被激发时,应用程序发送 QTimerEvent ,并控制流离开事件循环,直到计时器事件被处理。这隐含计时器无法被激发,当应用程序忙于做某些事情时。换句话说:计时器精度从属应用程序粒度。

在多线程应用程序中,可以在任何拥有事件循环的线程中使用计时器机制。要从非 GUI 线程启动事件循环,使用 QThread::exec ()。Qt 使用对象的 线程倾向性 确定哪个线程将交付 QTimerEvent 。因此,必须启动和停止对象线程中的所有计时器;为另一线程中的对象启动计时器,是不可能的。

间隔值上限可以由按有符号整数指定的毫秒数确定 (在实践中,此周期刚刚超过 24 天)。精度从属底层操作系统。Windows 2000 拥有 15 毫秒精度;测试过的其它系统,可以处理 1 毫秒间隔。

计时器功能的主要 API 是 QTimer 。该类提供发射信号的常规计时器当计时器被激发时,且继承 QObject so that it fits well into the ownership structure of most GUI programs. The normal way of using it is like this:

    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(updateCaption()));
    timer->start(1000);
					

QTimer object is made into a child of this widget so that, when this widget is deleted, the timer is deleted too. Next, its timeout() signal is connected to the slot that will do the work, it is started with a value of 1000 milliseconds, indicating that it will time out every second.

QTimer 还为单发计时器提供静态函数。例如:

    QTimer::singleShot(200, this, SLOT(updateCaption()));
					

200 milliseconds (0.2 seconds) after this line of code is executed, the updateCaption() slot will be called.

For QTimer to work, you must have an event loop in your application; that is, you must call QCoreApplication::exec () somewhere. Timer events will be delivered only while the event loop is running.

In multithreaded applications, you can use QTimer in any thread that has an event loop. To start an event loop from a non-GUI thread, use QThread::exec ()。Qt 使用计时器的 线程倾向性 确定哪个线程将发射 timeout() 信号。因此,必须在其线程中启动和停止计时器;从另一线程启动计时器,是不可能的。

指针式时钟 范例展示如何使用 QTimer 以按定期间隔重新绘制 Widget。来自 AnalogClock 的实现:

AnalogClock::AnalogClock(QWidget *parent)
    : QWidget(parent)
{
    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(update()));
    timer->start(1000);
    ...
}
					

每秒, QTimer 会调用 QWidget::update () 槽以刷新时钟的显示。

If you already have a QObject subclass and want an easy optimization, you can use QBasicTimer 而不是 QTimer 。采用 QBasicTimer ,必须重实现 timerEvent() 在您的 QObject subclass and handle the timeout there. The Wiggly 范例展示如何使用 QBasicTimer .