QTimer
(一)基本使用
timer.setInterval(1000); 设置间隔
connect(&timer, &QTimer::timeout, this, [&](){ ... }); 监听定时器
timer.start(); 开启定时器
timer.stop();
bool ret = timer.isActive(); 定时器是否开启
int ret = timer.remainingTime() 距离定时器触发, 还剩多长时间
定义定时器对象:QTimer *myTimer;
动态分部内存空间:myTimer = new QTimer(this);
启动定时器:myTimer->start(100);
定时器超时事件:QTimer::timeout()
停止定时器:myTimer->stop();
(二)详解
1.QTimer::singleShot()
这个静态函数在一个给定时间间隔 msec(毫秒) 之后调用一个槽。
Note: This function is reentrant.
//参数:(定时时间,接受者,槽函数) QTimer::singleShot(1000,this,[=]{ //想要执行的代码 qDebug() << "hello world" ; });
例子:返回上一级
//延时返回 QTimer::singleShot(500,[=](){ emit this->chooseSceneBack(); });
注意点:
1.无法显示按键效果
qDebug() << "zoom111"; startBtn->zoom();//按键效果动画 qDebug() << "zoom222"; chooseScene->setGeometry(this->geometry()); this->hide(); chooseScene->show();
void MyPushButton::zoom(){ ... qDebug() << "singleShot 111"; QTimer::singleShot(9000, this, [=]() {//停很久9000ms qDebug() << "singleShot internal"; }); ... qDebug() << "singleShot 222"; }
输出结果:
无法在跳转前延时来显示按键动画
解决方案:
connect(startBtn,&MyPushButton::clicked,[=](){ startSound->play(); startBtn->zoom(); //延时进入到选择关卡场景中 QTimer::singleShot(500,this,[=](){ chooseScene->setGeometry(this->geometry()); this->hide(); chooseScene->show(); }); });
2.通过QTimer做动画
//初始化定时器对象 timer1 = new QTimer(this); timer1->start(30); //监听正面翻反面的信号 , 并且翻转金币 connect(timer1,&QTimer::timeout,[=](){ QPixmap pix; QString str = QString("res/Coin000%1").arg(this->min++); pix.load(str); this->setFixedSize(pix.width(),pix.height()); this->setStyleSheet("QPushButton{border:0px}"); this->setIcon(pix); this->setIconSize(QSize(pix.width(),pix.height())); //判断 如果翻完了,将min重置为1 if(this->min > this->max) { this->min = 1; isAnimation = false; //停止做动画了 timer1->stop(); } });
实现连续翻转
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了