直接上代码:
textticker.h
#ifndef TEXTTICKER_H
#define TEXTTICKER_H#include <QWidget>
#include <QLabel>
#include <QString>
#include <QTimer>
#include <QPen>
#include <QFont>
#include <QPainter>
#include <QDebug>class TextTicker : public QLabel
{Q_OBJECT
public:TextTicker(QWidget *parent = 0);~TextTicker();protected:void paintEvent(QPaintEvent *event);void updateIndex();private:int m_charWidth;int m_stringWidth ;int m_curIndex;int m_pos;int pointSize ;QString m_showText;};#endif // TEXTTICKER_H
textticker.cpp
#include "textticker.h"TextTicker::TextTicker(QWidget *parent):QLabel(parent)
{this->setFixedSize(1920,114);QFont ft;pointSize = 44;ft.setPointSize(pointSize);this->setFont(ft);QPalette pa;pa.setColor(QPalette::WindowText,Qt::white);this->setPalette(pa);m_curIndex = 0;//当前角码m_pos = 0 ;m_showText = QStringLiteral("欢迎使用Qt");;//显示的文字m_charWidth =fontMetrics().width("欢");//每个字符的宽度m_stringWidth = fontMetrics().width(QStringLiteral("欢迎使用Qt"));qDebug()<<m_charWidth<<" "<<m_stringWidth;QTimer *timer = new QTimer(this);timer->setInterval(10);connect(timer, &QTimer::timeout, this, &TextTicker::updateIndex);timer->start();
}TextTicker::~TextTicker()
{}void TextTicker::paintEvent(QPaintEvent *event)
{QPen pen;pen.setColor(QColor(Qt::white));pen.setStyle(Qt::DashDotDotLine);int hPos = height()/2 + pointSize/2 ;QPainter painter(this);painter.setPen(pen);if(m_pos > m_stringWidth)painter.drawText(-(m_pos),hPos,m_showText);painter.drawText(width()-m_pos,hPos,m_showText.left(m_curIndex));
}void TextTicker::updateIndex()
{update();m_pos +=2 ;if(m_pos > width()+m_stringWidth)m_pos = 0 ;m_curIndex = m_pos/m_charWidth+1;
}
这份代码现在,不断的刷新绘制的时候,如果速度加快,会发现明显的抖动。