QT 定时器 QTimer 使用
目录
The QTimer class provides repetitive and single-shot timers. This class provide a high level programming interface for timers.
QTimer类提供重复和单次的定时器。
一、QTimer类使用
1、使用start开启 重复循环定时任务
First create a QTimer and then connect the timeout() signal to the appropriate slots. Call start() on the timer. From then on the timer will emit the timeout() signal at constant intervals.
首先创建一个 QTimer,然后将 timeout() 信号连接到适当的槽。 在计时器上调用 start()。 从那时起,计时器将以恒定的时间间隔发出 timeout() 信号。
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(update()));
timer->start(1000);
每一秒执行一次update()
In the example above, the update()
slot is called once every second.
2、单次延迟任务
void QTimer::singleShot ( int msec,
const QObject * receiver,
const QString & slotMethod
)
QTimer::singleShot(200, this, SLOT(updateCaption()));
又如:
#include <QApplication>
#include <QTimer>
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QTimer::singleShot(600000, &app, SLOT(quit()));
...
return app.exec();
}
3、超时为0的任务
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(processOneThing()));
timer->start();
超时为 0 的 QTimer 将在处理完窗口系统事件队列中的所有事件后立即超时。 这可以用来做繁重的工作,同时提供一个活泼的用户界面:
4、一个综合点的例子
recordingTimerDisplay = new QTimer(this);
QObject::connect(recordingTimerDisplay, SIGNAL(timeout()), this,
SLOT(UpdateRecordTimerDisplay()));
recordingTimerDisplay->start(1000);
if (recordingTimerDisplay->isActive())
recordingTimerDisplay->stop();
recordingTimer = new QTimer(this);
int total = (((hours * 3600) +
(minutes * 60)) +
seconds) * 1000;
if (total == 0)
total = 1000;
recordingTimer->setInterval(total);
recordingTimer->setSingleShot(true);
QObject::connect(recordingTimer, SIGNAL(timeout()),
SLOT(EventStopRecording()));
recordingTimer->start();
if (recordingTimer->isActive())
recordingTimer->stop();