QPropertyAnimation类定义了Qt的属性动画。
QPropertyAnimation以Qt属性做差值,作为属性值存储在QVariants中,该类继承自QVariantAnimation,并支持基类相同的元类型动画。
声明属性的类必须是一个QObject,为了能够让属性可以用做动画效果,必须提供一个setter(这样,QPropertyAnimation才可以设置属性的值)。注意:这能够使它让许多Qt控件产生动画效果。
来看一个示例:
QPropertyAnimation *animation = new QPropertyAnimation(myWidget, "geometry");
animation->setDuration(10000);
animation->setStartValue(QRect(0, 0, 100, 30));
animation->setEndValue(QRect(250, 250, 100, 30));animation->start();
首先,我们通过构造函数创建一个QPropertyAnimation对象,其中myWidget表示动画作用的QObject对象,geometry则表示QObject的属性。然后,可以指定属性的开始值和结束值。此过程等于在你自己的类中实现了自定义属性 - 需要用QVariantAnimation检测你自定义的QVariant类型是否支持。
QVariantAnimation类详细的描述了如何设置动画。需要注意的是:如果没有设置起始值,在QPropertyAnimation实例被创建时,属性就会设置起始值为它有的值。
QPropertyAnimation就其本身而言非常奏效。对于复杂的动画,例如:包含多个对象,则可以使用QAnimationGroup,动画组是一个可以包含其它动画的动画,并可以管理动画的播放。可以参考QParallelAnimationGroup的示例。
QByteArray propertyName() const
返回动画的目标属性名
void setPropertyName(const QByteArray & propertyName)
设置动画的目标属性名
void setTargetObject(QObject * target)
设置动画作用的QObject对象
QObject * targetObject() const
返回动画作用的QObject对象
下面,利用上面讲解的geometry属性,来实现一个动画坐标变化。
QPropertyAnimation *pAnimation = new QPropertyAnimation(m_pLabel, "geometry");
pAnimation->setDuration(1000);
pAnimation->setStartValue(QRect(0, 0, 75, 25));
pAnimation->setEndValue(QRect(200, 130, 75, 25));
pAnimation->setEasingCurve(QEasingCurve::OutBounce); // 缓和曲线风格
connect(pStartButton, SIGNAL(clicked(bool)), pAnimation, SLOT(start()));
通过自定义属性alpha,来使用动画设置标签的样式。
#ifndef MAIN_WINDOW_H
#define MAIN_WINDOW_H...class MainWindow : public CustomWindow
{Q_OBJECTQ_PROPERTY(int alpha READ alpha WRITE setAlpha)public:explicit MainWindow(QWidget *parent = 0);~MainWindow();private:int alpha() const;void setAlpha(const int alpha);private:int m_nAlpha;QLabel *m_pLabel;
};#endif // MAIN_WINDOW_H
#include "main_window.h"MainWindow::MainWindow(QWidget *parent): CustomWindow(parent)
{...QPushButton *pStartButton = new QPushButton(this);pStartButton->setText(QString::fromLocal8Bit("开始动画"));m_pLabel = new QLabel(this);m_pLabel->setText(QString::fromLocal8Bit("一去丶二三里"));m_pLabel->setAlignment(Qt::AlignCenter);m_pLabel->setStyleSheet("color: rgb(0, 160, 230);");QPropertyAnimation *pAnimation = new QPropertyAnimation();pAnimation->setTargetObject(this);pAnimation->setPropertyName("alpha");pAnimation->setDuration(1000);pAnimation->setKeyValueAt(0, 255);pAnimation->setKeyValueAt(0.5, 100);pAnimation->setKeyValueAt(1, 255);pAnimation->setLoopCount(-1); //永远运行,直到stopconnect(pStartButton, SIGNAL(clicked(bool)), pAnimation, SLOT(start()));...
}int MainWindow::alpha() const
{return m_nAlpha;
}void MainWindow::setAlpha(const int alpha)
{m_nAlpha = alpha;QString strQSS = QString("color: rgb(0, 160, 230); background-color: rgba(10, 160, 105, %1);").arg(m_nAlpha);m_pLabel->setStyleSheet(strQSS);
}
O(∩_∩)O~是不是很easy,如果你想要实现更多其它效果,都可以自定义。但一定要注意以下两点:
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态