qt中的定时器分为两种:widget和qml中的
1 widget
(1) Qt单次定时器
下面为两种实现方式,实现1秒单次定时器。 实现一 使用定时器QTimer的setSingleShot接口实现单次定时器。
#include <QTimter>QTimer *timer = new QTimer(this);connect(timer, SIGNAL(timeout()), SLOT(onTimeout()));timer->setSingleShot(true);timer->start(1000);
实现二
使用定时器QTimer的singleShot静态接口实现单次定时器,实现更简洁,推荐使用。
/* 信号槽 */QTimer::singleShot(1000, this, SLOT(onTimeout()));/* lambda */QTimer::singleShot(1000, [](){qDebug() << "Hello world!";});
2 qml中的
import QtQuick.Controls 1.2QtObject {id: attrsproperty int count;Component.onCompleted: {attrs.count = 3;}}Timer {id: countDowninterval: 1000repeat: truetriggeredOnStart: trueonTriggered: {attrs.count -= 1;if (attrs.count < 0){countDown.stop();/*执行*/attrs.count = 2;}}}countDown.start()}
