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();
        }
  });
复制代码

实现连续翻转

 

posted @   ImreW  阅读(70)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示