關於qt 實現laber上面的文字滾動


寫代碼前。首先我們肯定要新建一個項目。

1.點擊文件新建文件或項目

2.選擇帶界面的。名稱自己寫。然后繼承widget。完成

 

3.這樣,我們就得到了一個空的gui項目了。

 

新建一個能實現文字滾動的頭.h文件和對應的.cpp文件

這一次選擇c++類。點擊下一步我們就會得到一個自己寫好名字的頭文件和源文件了

 

 接下來就是代碼了。這是頭文件

隨便提一下,這里我們重寫了laber的繪畫事件

以及新建了一個更新需要滾動的文字下標值類。

 1 #include <QLabel>
 2 
 3 class TextTicker : public QLabel
 4 {
 5     Q_OBJECT
 6 
 7 
 8 public:
 9     TextTicker(QWidget *parent = nullptr);
10     ~TextTicker();
11 
12 
13 protected:
14     void paintEvent(QPaintEvent *);
15     void updateIndex();
16 
17 private:
18     int m_charWidth; //字符串寬度
19     int m_curIndex;
20     QString m_showText; //需要顯示的字符串
21 public:
22 
23     QString getText()
24     {
25         return  m_showText;
26     }
27 };

接下來是源文件

這里預編譯這里注意添加上自己的頭文件  #include "xxx.h"

#include <QPainter>
#include <QTimer>


TextTicker::TextTicker(QWidget *parent)
    : QLabel(parent)
{
//    setMinimumWidth(200);
//    setMinimumHeight(40);


    m_curIndex = 0;//當前文字下標值
    m_showText = tr("Welcome to the image processing software of Star Dragon Company");//顯示的文字


    m_charWidth = fontMetrics().width("a");//每個字符的寬度


    QTimer *timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &TextTicker::updateIndex);
    timer->start(100);
}


TextTicker::~TextTicker()
{


}


void TextTicker::paintEvent(QPaintEvent *)
{
    QPen pen;
    pen.setColor(QColor(255,0,255));

       pen.setStyle(Qt::DashDotDotLine);

       QFont font("楷體",14,QFont::Bold);

       
    QPainter painter(this);
    painter.setPen(pen);

    painter.setFont(font);
    painter.drawText(0, 15, m_showText.mid(m_curIndex));
    painter.drawText(width() - m_charWidth*m_curIndex, 15, m_showText.left(m_curIndex));
}


void TextTicker::updateIndex()
{
    update();
    m_curIndex++;
    if (m_curIndex*m_charWidth > width())
        m_curIndex = 0;
}

  到這里基本就完成了。

接下來要做的就是在gui拖入一個laber控件。右鍵點擊提升。類名填寫我們創建的類,注意。如果頭文件跟類名不一致,注意對應填寫即可。

然后運行。試試效果把。

自己做項目中遇到的記錄下來。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM