QTimer是一个定时器工具类,定时器就是在间隔一定时间后去执行某个任务。如:广告弹窗自动关闭,消息自动关闭......
QTimer *timer1 = new QTimer(this);
timer->start(1000);启动计时器,1000ms触发一次
connect(timer, &QTimer::timeout, this,[=](){
qDebug()<<"1s";
});
timer->stop();//停止计时器
Q_SIGNALS:
void timeout(QPrivateSignal);
单次触发定时器
在某些应用场景中,只需要定时器触发一次而不是周期性触发。为此,QTimer
提供了单次触发模式,可以通过 setSingleShot(true)
方法或 QTimer::singleShot()
静态方法实现。
void setSingleShot(bool singleShot)
QTimer *timer1 = new QTimer(this);
timer->start(3000);
timer->setSingleShot(true);//设置为单次触发
connect(timer, &QTimer::timeout, this,[=](){
QMessageBox::information(this,"广告","特价");
});
使用 QTimer::singleShot()
静态方法,可以简化单次触发定时器的使用。通过这个方法,可以直接设置一个单次触发的定时器,并指定超时时间和槽函数。
QTimer::singleShot(3000,[=](){
QMessageBox::information(this,"广告","特价");
});