35 Qt drawing blinking text

Brief description

According to the previous two-dimensional drawing, we can easily draw the text, if we need some special effects, such as: text flashing. We must use other auxiliary classes to complete.

principle

Mainly involves two auxiliary categories:

  1.     QFontMetrics is used to get the pixel height and width of the text font
  2.     QBasicTimer timer, used to update text drawing.

principle:

    Use QBasicTimer to refresh regularly.

    When drawing text, use QColor to set the hue (H), saturation (S), and brightness (V), and then calculate the drawing coordinates of each character for a single drawing.

Source code

The header file BannerWidget.h

#ifndef PARA_BANNER_H
#define PARA_BANNER_H

#include <QWidget>
#include <QBasicTimer>

class BannerWidget : public QWidget
{
    Q_OBJECT
public:
    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_strText;
    int m_nStep;
};

#endif

Source file BannerWidget.cpp

#include <QPainter>
#include <QTimerEvent>
#include <QFont>
#include "BannerWidget.h"

BannerWidget::BannerWidget(QWidget *parent)
    : QWidget(parent),
      m_nStep(0),
      m_strText(QString::fromLocal8Bit("一去丶二三里"))
{
    setAutoFillBackground(true);

    // 设置文字大小
    QFont newFont = font();
    newFont.setPointSize(newFont.pointSize() + 20);
    setFont(newFont);

    m_timer.start(100, this);
}

BannerWidget::~BannerWidget()
{
    m_timer.stop();
}

void BannerWidget::setText(const QString &text)
{
    m_strText = 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;
        update();
    }
    else
    {
        QWidget::timerEvent(event);
    }
}

Of course, we can also modify the values ​​of the starting coordinates x and y. After a little change, the text will have a jumping effect. Try it yourself!

Guess you like

Origin blog.csdn.net/Chiang2018/article/details/102773203