1. 程式人生 > >Qt 之滾動字幕

Qt 之滾動字幕

簡述

滾動字幕,也就是傳說中的跑馬燈效果。

​簡單地理解就是:每隔一段時間(一般幾百毫秒效果較佳)顯示的文字進行變化(即滾動效果)。

|

實現

利用定時器QTimer,在固定的時間(這裡為200毫秒)擷取文字,來實現滾動效果!

效果

這裡寫圖片描述

原始碼

首先,我們需要定義顯示的滾動字幕:

const QString strScrollCation = QString::fromLocal8Bit("一去丶二三裡 - 青春不老,奮鬥不止!");

定義QLabel進行文字的顯示,利用QTimer定時更新。

m_pLabel = new QLabel(this);

QTimer *pTimer = new
QTimer(this); connect(pTimer, SIGNAL(timeout()), this, SLOT(scrollCaption())); // 定時200毫秒 pTimer->start(200);

實現槽函式,進行滾動更新:

void MainWindow::scrollCaption()
{
    static int nPos = 0;

    // 當擷取的位置比字串長時,從頭開始
    if (nPos > strScrollCation.length())
        nPos = 0;

    m_pLabel->setText(strScrollCation.mid(nPos));
    nPos++;
}