Qt时间轴QTimeLine的基本用法
概述
QTimeLine類提供用于控制動畫的時間表,通常用于定期調用插槽來為GUI控件創建動畫。簡單來說,就是可以通過 QTimeLine 來快速的實現動畫效果,其原理就是在指定的時間內發出固定幀率的信號,通過連接該信號去改變目標控件的值,由于時間斷幀率高,所以整體看起來就是連續的動畫效果。
以上說得可能有些抽象,下面結合實例和用法步驟來看看。
用法
將使用步驟總結為以下幾點:
- 1.創建 QTimeLine對象的時候傳入時間值,單位是毫秒,該時間就是動畫運行的時間;
- 2.設置幀率范圍,通過setFrameRange()進行設置,該值表示在規定的時間內將要執行多少幀;
- 3.連接frameChanged()信號,并在槽中對需要實現動畫的控件進行賦值,如QProgressBar的setValue().
- 4.調用 start()開始執行時間軸動作。
當 QTimeLine調用 start()后將進入運行狀態,并會發出frameChanged()信號,而連接該信號的槽中將會不斷的對目標控件進行相應的動作賦值,從而實現動畫效果。可以通過調用setUpdateInterval()來指定更新間隔。完成后,QTimeLine進入NotRunning狀態,并發出finished().
簡單示例
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()));當點擊按鈕后,progressBar 將會在1000ms 內進行100次setValue(),這里的timeLine->setFrameRange(0, 100);表示將執行100幀,也就是說會發出100次frameChanged信號,通過連接該信號去改變progressBar的值。
默認情況下,時間軸從開始到結束運行一次,此時必須再次調用start()才能從頭開始重新啟動。要進行時間線循環,您可以調用setLoopCount(),并在完成之前傳遞時間軸應該運行的次數。通過調用setDirection(),方向也可以改變,可以讓時間線向后運行。也可以通過調用setPaused()來暫停和取消暫停時間軸的運行。對于交互式控件,提供了setCurrentTime()函數,該函數直接設置時間線的時間位置。
再來看一個示例:
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()));效果:
這里通過連接信號finished,當一次動畫結束后再調用setDirection來改變動畫方向。
更多用法,查看 Qt 幫助文檔 http://doc.qt.io/qt-5/qtimeline.html
總結
以上是生活随笔為你收集整理的Qt时间轴QTimeLine的基本用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Qt之QTemporaryDir用法(创
- 下一篇: Qt之Q_GLOBAL_STATIC创建