#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 <QPainter>
#include <QTimer>
TextTicker::TextTicker(QWidget *parent)
: QLabel(parent)
{
m_curIndex = 0;
m_showText = tr("不想学Qt");
m_charWidth = fontMetrics().width("a");
QTimer *timer = new QTimer(this);
connect(timer, &QTimer::timeout, this, &TextTicker::updateIndex);
timer->start(500);
}
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);
QPalette palette;
palette.setColor(QPalette::Background,QColor(1,1,1));
setAutoFillBackground(true);
setPalette(palette);
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;
}