标签:
滚动字幕,也叫跑马,就是动态显示一行字符。前面实现是使用QTimer控制,直接在槽函数中截取字符串进行显示,只控制字符串在控件的一端显示,超出控件的部分并没有从控件的另一端循环显示出来。于是我重新实现了一种方法,或者说完善了前面的不足吧。fontMetrics().width("a");//每个字符的宽度完整示例代码:
#ifndef TEXTTICKER_H #define TEXTTICKER_H #include <QtWidgets/QLabel> 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_curIndex; QString m_showText; }; #endif // TEXTTICKER_H
#include "textticker.h" #include <QPainter> #include <QTimer> TextTicker::TextTicker(QWidget *parent) : QLabel(parent) { setMinimumWidth(200); setMinimumHeight(40); m_curIndex = 0;//当前角码 m_showText = "This is a textTicker Text!";//显示的文字 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 *event) { __super::paintEvent(event); QPainter painter(this); painter.drawText(0, 30, m_showText.mid(m_curIndex)); painter.drawText(width() - m_charWidth*m_curIndex, 30, m_showText.left(m_curIndex)); } void TextTicker::updateIndex() { update(); m_curIndex++; if (m_curIndex*m_charWidth > width()) m_curIndex = 0; }交流QQ:1245178753
标签:
原文地址:http://blog.csdn.net/u011417605/article/details/51211853