Qt实现文字滚动、翻动动画方式不唯一,这里尝试了2个手段。
-
基于动画类:QPropertyAnimation
-
使用QLabel的QPainter动态绘制
具体来看:
A.使用动画类QPropertyAnimation:
具体可以参考blog:https://www.cnblogs.com/lvdongjie/p/4366092.html
简单来说,就几句话:
QPropertyAnimation在内的一簇类是Qt里用来实现动画的
QPropertyAnimation的动画可以针对所有的QWidget控件进行动态属性变化
位置类的变化(geometry):简单的可以设置起点、终点、大小、运动时间,然后就自动完成动作
// init
m_TopPropertyAnimation = new QPropertyAnimation(this);
// bind
m_TopPropertyAnimation->setTargetObject(m_TopLabel);
m_TopPropertyAnimation->setPropertyName("geometry");
// set 动画的起点、终点、持续时间
m_TopPropertyAnimation->setDuration(1000);
m_TopPropertyAnimation->setStartValue(QRect(0, 0, width, height));
m_TopPropertyAnimation->setEndValue(QRect(0, -height, width, height));
// 启动和结束
m_TopPropertyAnimation->start();
m_TopPropertyAnimation->stop();
B.使用空间的QPainter绘制功能:
这个思路:是将显示的内容做动态绘制,应该能实现的是图片和文字。
关键在于,重写paintEvent:
void TextTicker::paintEvent(QPaintEvent *event)
{
// __super::paintEvent(event);
QPainter painter(this);
painter.drawText(0 - m_curIndex, 30, m_showText);
painter.drawText(m_totalWidth - m_curIndex, 30, m_showText);
}
这个paintEvent需要基于一个自定义的计时器来触发,从而形成连贯动画
QTimer *timer = new QTimer(this);
connect(timer, &QTimer::timeout, this, &TextTicker::updateIndex);
timer->start(60);
void TextTicker::updateIndex()
{
update();
m_curIndex++;
if (m_curIndex > m_totalWidth)
{
m_curIndex = 0;
}
}