Qt 绘制炫彩滚动文本

来源:互联网 发布:房地产投资 知乎 编辑:程序博客网 时间:2024/04/28 09:35

参考 Qt之滚动字幕
………Qt之闪烁文本

简述

继承 QWidget 类,完成滚动文本,并且每次字体是炫彩颜色,每次循环,炫彩的颜色都不同。

  • 简述
  • 效果
  • 源码
    • 类的实现
    • 类的使用

效果

这里写图片描述

源码

类的实现

// BannerWidget.h#ifndef PARA_BANNER_H#define PARA_BANNER_H#include <QWidget>#include <QBasicTimer>class BannerWidget : public QWidget{    Q_OBJECTpublic:    explicit BannerWidget(QWidget *parent = 0);    ~BannerWidget();    public slots:    void setText(const QString &text);protected:    // 绘制文本    void paintEvent(QPaintEvent *event);    // 定时刷新    void timerEvent(QTimerEvent *event);private:    QBasicTimer m_timer;    QString m_strTextPre;    QString m_strText;    int m_nStep;};#endif
// BannerWidget.cpp#include <QPainter>#include <QTimerEvent>#include <QFont>#include "BannerWidget.h"BannerWidget::BannerWidget(QWidget *parent)    : QWidget(parent)    ,m_nStep(0)    ,m_strText("")    , m_strTextPre(QStringLiteral("学习编程,乐在其中!")){    setAutoFillBackground(true);    // 设置文字大小    QFont newFont = font();    newFont.setPointSize(newFont.pointSize() + 20);    setFont(newFont);    m_timer.start(1000, this);}BannerWidget::~BannerWidget(){    m_timer.stop();}void BannerWidget::setText(const QString &text){    m_strTextPre = text;}void BannerWidget::paintEvent(QPaintEvent *event){    Q_UNUSED(event);    // 计算文本绘制的起始坐标    QFontMetrics metrics(font());    int x = (width() - metrics.width(m_strText)) / 2;    int y = (height() + metrics.ascent() - metrics.descent()) / 2;    QColor color;    QPainter painter(this);    for (int i = 0; i < m_strText.size(); ++i)    {        // 设置色调(H)、饱和度(S)、亮度(V)        int nIndex = (m_nStep + i) % 16;        color.setHsv((15 - nIndex) * 16, 255, 191);        painter.setPen(color);        // 单个字符绘制        painter.drawText(x, y, QString(m_strText[i]));        // 计算下一个字符的x坐标起始点        x += metrics.width(m_strText[i]);    }}void BannerWidget::timerEvent(QTimerEvent *event){    Q_UNUSED(event);    if (event->timerId() == m_timer.timerId())    {        ++m_nStep;        // 当 m_nStep 超过int的最大值时,就会变成负数!从0重新计数。        if (m_nStep < 0)            m_nStep = 0;        static int nPos = m_strTextPre.length();        static bool bAddIndex = false;        update();        if (bAddIndex)        {            m_strText = m_strTextPre.left(nPos);            nPos++;        }        else        {            m_strText = m_strTextPre.right(nPos);            nPos--;        }        if (nPos >= m_strTextPre.length())            bAddIndex = false;        if (nPos <= 0)            bAddIndex = true;    }    else    {        QWidget::timerEvent(event);    }}

类的使用

void StudyDraw::drawBulingText(){    BannerWidget *wgt = new BannerWidget(this);    QVBoxLayout * layOut = new QVBoxLayout(this);    layOut->addWidget(wgt);    ui->centralWidget->setLayout(layOut);}