一、单次定时器
1、QTimer::singleShot
简单但无法控制(无法中止已开始的定时器)
//延时10毫秒执行load函数
QTimer::singleShot(10, this, SLOT(load()));
//定时器lambda表达式方式
QTimer::singleShot(10, [&]() {
load();
});
2、QTimer::setSingleShot
可中止该单次定时器
QTimer *timer = new QTimer(this);
timer->setSingleShot(true);
connect(timer, &QTimer::timeout, this, [this] {
//....
});
timer->start(5000);
二、定时器首次超时与之后超时间隔不一致实现
在有些需求中,需要定时器首次与之后固定超时时间不一致
QTimer默认不支持首次超时与之后超时不一致
可以使用2个定时器来实现
QTimer* timer2 = new QTimer(this);
timer2->setInterval(1000);
connect(timer2, &QTimer::timeout, this, [timer2, this] {
//...
});
QTimer *timer = new QTimer(this);
timer->setSingleShot(true);
connect(timer, &QTimer::timeout, this, [timer, this] {
timer2->start();
});
timer->start(5000);