qt中的定时器分为两种:widget和qml中的

1 widget

(1) Qt单次定时器

下面为两种实现方式,实现1秒单次定时器。 实现一 使用定时器QTimer的setSingleShot接口实现单次定时器。
  1. #include <QTimter>
  2. QTimer *timer = new QTimer(this);
  3. connect(timer, SIGNAL(timeout()), SLOT(onTimeout()));
  4. timer->setSingleShot(true);
  5. timer->start(1000);

实现二

使用定时器QTimer的singleShot静态接口实现单次定时器,实现更简洁,推荐使用。
  1. /* 信号槽 */
  2. QTimer::singleShot(1000, this, SLOT(onTimeout()));
  3. /* lambda */
  4. QTimer::singleShot(1000, [](){qDebug() << "Hello world!";});

2 qml中的

  1. import QtQuick.Controls 1.2
  2. QtObject {
  3. id: attrs
  4. property int count;
  5. Component.onCompleted: {
  6. attrs.count = 3;
  7. }
  8. }
  9. Timer {
  10. id: countDown
  11. interval: 1000
  12. repeat: true
  13. triggeredOnStart: true
  14. onTriggered: {
  15. attrs.count -= 1;
  16. if (attrs.count < 0){
  17. countDown.stop();
  18. /*
  19. 执行
  20. */
  21. attrs.count = 2;
  22. }
  23. }
  24. }
  25. countDown.start()
  26. }