学习笔记(4):状态机与动画结合

来源:互联网 发布:林黛玉漂亮吗 知乎 编辑:程序博客网 时间:2024/06/17 14:20

学习日记一和学习日记二分别学习了Qt动画框架和Qt状态机框架。 今天学习如何将两者结合起来。

回顾一下状态机的几个要素:状态机、状态、切换(QTransition)。   

        那么如何在加入动画呢,其实很简单,我们通过切换来改变状态,在切换中加入动画就行了。

直接上例子:

 QStateMachine* stateMachine = new QStateMachine;  //创建状态机    //创建状态1    QState* showState = new QState(stateMachine);    showState->assignProperty(ui->pushButton_2,"geometry",QRect(100,100,120,30));    showState->assignProperty(ui->pushButton_2,"opacity",1.0);    //创建状态2    QState* hideState = new QState(stateMachine);    hideState->assignProperty(ui->pushButton_2,"geometry",QRect(0,0,1,1));    hideState->assignProperty(ui->pushButton_2,"opacity",0.1);    //添加状态1的切换,  为切换添加动画    QSignalTransition* showTransition = showState->addTransition(this,SIGNAL(sig_hide()),hideState);    QPropertyAnimation* geoAnimation = new QPropertyAnimation(ui->pushButton_2,"geometry");    geoAnimation->setDuration(2000);    geoAnimation->setEasingCurve(QEasingCurve::InOutBounce);    QPropertyAnimation* opyAnimation = new QPropertyAnimation(ui->pushButton_2,"opacity");    opyAnimation->setDuration(2000);    showTransition->addAnimation(geoAnimation);    showTransition->addAnimation(opyAnimation);    //添加状态2的切换,为切换添加动画    QSignalTransition* hideTransition = hideState->addTransition(this,SIGNAL(sig_show()),showState);    QPropertyAnimation* geoAnimation2 = new QPropertyAnimation(ui->pushButton_2,"geometry");    geoAnimation2->setDuration(2000);    geoAnimation2->setEasingCurve(QEasingCurve::OutCirc);    QPropertyAnimation* opyAnimation2 = new QPropertyAnimation(ui->pushButton_2,"opacity");    opyAnimation2->setDuration(2000);    hideTransition->addAnimation(geoAnimation2);    hideTransition->addAnimation(opyAnimation2);    stateMachine->setInitialState(hideState); //设置初始化状态    stateMachine->start(); //启动状态机

用UI设计师在Widget中添加了两个按钮,ui->pushButton和ui->pushButton_2  。    为ui->pushButton添加一个按下的槽函数。分别触发sig_show()和sig_hide()两个信号。


通过这两个信号来改变ui->pushButton_2的状态。



总结今天的内容就是一个函数:QSignalTransition::addAnimation();    值得注意的是我们这里的动画没有设置值(setKeyValueAt()),这里的值会根据状态中的值来变化,比如:从状态1到状态2    按钮2的几何会从QRect(100,100,120,30)   到 QRect(0,0,1,1)。

还有就是opacity不是按钮的属性,不能用于动画,提示:QPropertyAnimation: you're trying to animate a non-existing property opacity of your QObject 。 至于怎么解决这个问题以后再说。


0 0