Qt时间轴QTimeLine的基本用法
概述
QTimeLine類提供用于控制動(dòng)畫的時(shí)間表,通常用于定期調(diào)用插槽來為GUI控件創(chuàng)建動(dòng)畫。簡(jiǎn)單來說,就是可以通過 QTimeLine 來快速的實(shí)現(xiàn)動(dòng)畫效果,其原理就是在指定的時(shí)間內(nèi)發(fā)出固定幀率的信號(hào),通過連接該信號(hào)去改變目標(biāo)控件的值,由于時(shí)間斷幀率高,所以整體看起來就是連續(xù)的動(dòng)畫效果。
以上說得可能有些抽象,下面結(jié)合實(shí)例和用法步驟來看看。
用法
將使用步驟總結(jié)為以下幾點(diǎn):
- 1.創(chuàng)建 QTimeLine對(duì)象的時(shí)候傳入時(shí)間值,單位是毫秒,該時(shí)間就是動(dòng)畫運(yùn)行的時(shí)間;
- 2.設(shè)置幀率范圍,通過setFrameRange()進(jìn)行設(shè)置,該值表示在規(guī)定的時(shí)間內(nèi)將要執(zhí)行多少幀;
- 3.連接frameChanged()信號(hào),并在槽中對(duì)需要實(shí)現(xiàn)動(dòng)畫的控件進(jìn)行賦值,如QProgressBar的setValue().
- 4.調(diào)用 start()開始執(zhí)行時(shí)間軸動(dòng)作。
當(dāng) QTimeLine調(diào)用 start()后將進(jìn)入運(yùn)行狀態(tài),并會(huì)發(fā)出frameChanged()信號(hào),而連接該信號(hào)的槽中將會(huì)不斷的對(duì)目標(biāo)控件進(jìn)行相應(yīng)的動(dòng)作賦值,從而實(shí)現(xiàn)動(dòng)畫效果。可以通過調(diào)用setUpdateInterval()來指定更新間隔。完成后,QTimeLine進(jìn)入NotRunning狀態(tài),并發(fā)出finished().
簡(jiǎn)單示例
progressBar = new QProgressBar(this); progressBar->setRange(0, 100); progressBar->move(100,100);// Construct a 1-second timeline with a frame range of 0 - 100 QTimeLine *timeLine = new QTimeLine(1000, this); timeLine->setFrameRange(0, 100); connect(timeLine, SIGNAL(frameChanged(int)), progressBar, SLOT(setValue(int)));// Clicking the push button will start the progress bar animation QPushButton * pushButton = new QPushButton(tr("Start animation"), this); connect(pushButton, SIGNAL(clicked()), timeLine, SLOT(start()));當(dāng)點(diǎn)擊按鈕后,progressBar 將會(huì)在1000ms 內(nèi)進(jìn)行100次setValue(),這里的timeLine->setFrameRange(0, 100);表示將執(zhí)行100幀,也就是說會(huì)發(fā)出100次frameChanged信號(hào),通過連接該信號(hào)去改變progressBar的值。
默認(rèn)情況下,時(shí)間軸從開始到結(jié)束運(yùn)行一次,此時(shí)必須再次調(diào)用start()才能從頭開始重新啟動(dòng)。要進(jìn)行時(shí)間線循環(huán),您可以調(diào)用setLoopCount(),并在完成之前傳遞時(shí)間軸應(yīng)該運(yùn)行的次數(shù)。通過調(diào)用setDirection(),方向也可以改變,可以讓時(shí)間線向后運(yùn)行。也可以通過調(diào)用setPaused()來暫停和取消暫停時(shí)間軸的運(yùn)行。對(duì)于交互式控件,提供了setCurrentTime()函數(shù),該函數(shù)直接設(shè)置時(shí)間線的時(shí)間位置。
再來看一個(gè)示例:
m_pWidget = new QWidget(this); m_pWidget->resize(50,50); m_pWidget->setStyleSheet("background-color:red;"); m_pWidget->move(0,100); m_pWidget->show();QTimeLine *timeLine = new QTimeLine(1000, this); timeLine->setFrameRange(0, 200); connect(timeLine,&QTimeLine::frameChanged,this,[=](int frame){m_pWidget->move(1*frame,100); }); connect(timeLine,&QTimeLine::finished,this,[=](){ if(timeLine->direction() == 0){timeLine->setDirection(QTimeLine::Backward); } else{timeLine->setDirection(QTimeLine::Forward); }timeLine->start(); });QPushButton * pushButton = new QPushButton(tr("Start animation"), this); connect(pushButton, SIGNAL(clicked()), timeLine, SLOT(start()));效果:
這里通過連接信號(hào)finished,當(dāng)一次動(dòng)畫結(jié)束后再調(diào)用setDirection來改變動(dòng)畫方向。
更多用法,查看 Qt 幫助文檔 http://doc.qt.io/qt-5/qtimeline.html
總結(jié)
以上是生活随笔為你收集整理的Qt时间轴QTimeLine的基本用法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Qt之QTemporaryDir用法(创
- 下一篇: Qt C++属性类型提供给 QML调用(