QTimeLine简述
它最常用于通过周期性调用槽来动画化GUI控件。您可以通过将时间线的持续时间(以毫秒为单位)传递给QTimeLine的构造函数来构造时间线。时间线的持续时间描述动画将运行多长时间。然后通过调用setFrameRange()设置合适的帧范围。最后,将frameChanged()信号连接到要设置动画的小部件中的适当插槽(例如,QProgressBar中的setValue())。当您继续调用start()时,QTimeLine将进入运行状态,并开始定期发出frameChanged(),从而使小部件的连接属性值以稳定的速度从下端增长到帧范围的上端。您可以通过调用setUpdateInterval()来指定更新间隔。完成后,QTimeLine进入NotRunning状态,并发出finished()。
一句话,QTimeLine类提供了控制动画的时间线。
QTimeLine的简单示例
#include <QTimeLine>
#include <QVBoxLayout>
#include <QProgressBar>
#include <QPushButton>
#include <QLabel>
#include <QTextEdit>
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
setFixedSize(QSize(600,400));
QVBoxLayout* layoutMain = new QVBoxLayout(this);
QProgressBar* progressBar = new QProgressBar(this);
progressBar->setRange(0, 100);
progressBar->setTextVisible(false);
QHBoxLayout* layoutButton = new QHBoxLayout;
layoutButton->addStretch(1);
QPushButton* butt = new QPushButton(tr("start animation"), this);
layoutButton->addWidget(butt);
QLabel* label = new QLabel(this);
label->setObjectName("labelStyle");
label->setFixedSize(QSize(100,50));
label->setStyleSheet("QLabel#labelStyle{background-color:red;}");
QTextEdit* editLog = new QTextEdit(this);
//
layoutMain->addStretch(1);
layoutMain->addWidget(progressBar);
layoutMain->addSpacing(10);
layoutMain->addWidget(label);
layoutMain->addSpacing(10);
layoutMain->addLayout(layoutButton);
layoutMain->addSpacing(10);
layoutMain->addWidget(editLog);
layoutMain->addStretch(1);
//
QTimeLine *timeLine = new QTimeLine(1500, this);
timeLine->setFrameRange(0, 100);//表示将执行100帧
timeLine->setCurveShape(QTimeLine::EaseInOutCurve);
//timeLine->setLoopCount(2);
connect(timeLine, &QTimeLine::frameChanged, this, [=](int frame){
//set progress
progressBar->setValue(frame);
//set geometry
QRect rc = this->geometry();
int step = (rc.width()-100) * 0.01;
int y = label->geometry().y();
label->move(step*frame, y);
//set style
QString qss = "QLabel#labelStyle{"
"background-color: qlineargradient(x1:0, y1:0, x2:1, y2:0,"
"stop:0.0 rgba(255, 38, 2, 255),"
"stop:1.0 rgba(%1, %2, 255, 255));}";
QString style = qss.arg(frame).arg(frame);
editLog->append(style);
label->setStyleSheet(style);
});
connect(timeLine, &QTimeLine::finished, this, [=](){
if(timeLine->direction() == 0){
timeLine->setDirection(QTimeLine::Backward);
}
else{
timeLine->setDirection(QTimeLine::Forward);
}
timeLine->start();
});
connect(butt, SIGNAL(clicked()), timeLine, SLOT(start()));
}