开发项目中学习到的知识,记录一下。文本在qlabel控件中来回滚动
- #ifndef SCROLLLABEL_H
- #define SCROLLLABEL_H
-
- #include
- #include
- #include
- #include
- class ScrollLabel : public QLabel
- {
- public:
- ScrollLabel(QWidget *parent = nullptr);
-
- public:
- void paintEvent(QPaintEvent *);
- void UpdateIndex();
- void StartScroll(int p_IsUp, QString p_Str1, QString p_Str2);
- void SetFont(QFont p_Font);
- void SetText(QString p_Str);
-
- private:
- QTimer *m_Timer;
- int m_CurIndex;
- int m_IsUp;
- QString m_Str1;
- QString m_Str2;
- QFont m_Font;
- };
-
- #endif // SCROLLLABEL_H
- #include "scrolllabel.h"
- #include
- #include
- #include
-
- ScrollLabel::ScrollLabel(QWidget *parent): QLabel(parent)
- {
- m_CurIndex = 0;
- m_Timer = new QTimer(this);
- m_Timer->setInterval(20);
- connect(m_Timer, &QTimer::timeout, this, &ScrollLabel::UpdateIndex);
- }
-
- void ScrollLabel::paintEvent(QPaintEvent *)
- {
- QPen pen;
- pen.setColor(QColor(255,255,255));
-
- QPainter painter(this);
- painter.setPen(pen);
- painter.setFont(m_Font);
-
- QFontMetrics FontMetrics(m_Font);
-
- int Str1Width = FontMetrics.width(m_Str1);//字符的宽度
- int Str2Width = FontMetrics.width(m_Str2);//字符的宽度
- int CharWidth = FontMetrics.width("a");//每个字符的宽度
-
- int Interval = (width() - Str1Width)/2;
- int Interval2 = (width() - Str2Width)/2;
-
- if(0 == m_CurIndex)
- {
- painter.drawText(Interval , 22, m_Str1);
- }
- else
- {
- if(m_IsUp)
- {
- painter.drawText(Interval+CharWidth*m_CurIndex, 22, m_Str1);
- painter.drawText(CharWidth*m_CurIndex - Str2Width + (Interval - Interval2), 22, m_Str2);
-
- if(Interval + CharWidth*m_CurIndex > width())
- {
- m_Timer->stop( );
- m_CurIndex = 0;
- }
- }
- else
- {
- painter.drawText((width() -Str1Width)/2-CharWidth*m_CurIndex, 22, m_Str1);
- painter.drawText(width() - CharWidth*m_CurIndex+(Interval2 - Interval), 22, m_Str2);
-
- if(Interval + Str1Width < CharWidth*m_CurIndex)
- {
- m_Timer->stop( );
- m_CurIndex = 0;
- }
- }
-
- }
- }
-
- void ScrollLabel::UpdateIndex()
- {
- update();
- m_CurIndex++;
- }
-
-
- void ScrollLabel::SetFont(QFont p_Font)
- {
- m_Font = p_Font;
- }
-
- void ScrollLabel::SetText(QString p_Str)
- {
- m_Str1 = p_Str;
- update();
- }
-
- void ScrollLabel::StartScroll(int p_IsUp, QString p_Str1, QString p_Str2)
- {
- m_IsUp = p_IsUp;
- m_Str1 = p_Str1;
- m_Str2 = p_Str2;
- m_Timer->start( );
- }
-
- 调用方法:
-
- m_total_mileage_text_label = new ScrollLabel(this);
-
- //开始滚动
- m_total_mileage_text_label->StartScroll(IsUp, Str1, Str2);
-
- IsUp 1:指滚向上一条 0:滚向下一条
- str1和str2分别指滚动前的字符串和滚动后的字符串