天天看點

Qt QLabel + 定時器 實作滾動字幕

//首先在你的工程裡要啟動一個定時器(定時器的觸發周期以100ms間隔為宜

void QWidgetProperty::timerEvent(QTimerEvent *evt)

{

    if (pageCaption->isVisible())//為了節省計算資源,確定你的界面可視情況下才滾動字幕

    {

       //記錄一下最後一次滾動時間,用來控制滾動速度

        static QDateTime dtLast = QDateTime::currentDateTime();

        QDateTime dtNow = QDateTime::currentDateTime();

        int delt = 100;

        switch (prevset.sys_marquee)

        {

        case 0: //不滾動

            return;

        case 1://速度1

        case 2://速度2

        case 3://速度3

        case 4://速度4

        case 5://速度5

            delt = 100 * (6 - prevset.sys_marquee);//間隔越小速度越快

            break;

        default://預設速度

            delt = 400;

            break;

        }

        if (dtLast.msecsTo(dtNow)>delt)

        {

            static int idx = 0;

            static int DELTA = 0;

            static QString strSpace = "";

            QFontMetrics fm = labelPreview->fontMetrics();

            int          w = fm.width(prevset.sys_caption);

            int          delt = labelPreview->width() - w;

            if (DELTA == 0 || DELTA != delt)

            {

                DELTA = delt;

                strSpace = "";

                while (fm.width(strSpace) < DELTA)

                {

                    strSpace.append("  ");

                }

            }

            QString      strNew = prevset.sys_caption + strSpace;

            QString      strHead = strNew.mid(0, idx);

            QString      strTail = strNew.mid(idx, strNew.length() - idx);

            if (idx < strNew.length())idx++;

            else     idx = 0;

            strTail.append(strHead);

            labelPreview->setText(strTail);

           dtLast = dtNow;//滾動的上一次時間

        }

    }

}