//实现一个渐变的文字
#include <QWidget>
#include <QPaintEvent>
class GraduateText : public QWidget
{
Q_OBJECT
public:
explicit GraduateText(QWidget *parent = nullptr);
//设置文字
void setText(const QString &text);
//设置文字大小
void setTextSize(int size);
//设置渐变颜色
void setGraduateColor(QColor startColor, QColor endColor);
protected:
void paintEvent(QPaintEvent * event);
private:
QString m_strText; //文字
int m_iTextSize; //文字大小
QColor m_startColor; //起始颜色
QColor m_endColor; //结束颜色
};
#include "GraduateText.h"
#include <QPainter>
#include <QPainterPath>
GraduateText::GraduateText(QWidget *parent) : QWidget(parent)
{
}
void GraduateText::setText(const QString &text)
{
m_strText = text;
update();
}
void GraduateText::setTextSize(int size)
{
m_iTextSize = size;
update();
}
void GraduateText::setGraduateColor(QColor startColor, QColor endColor)
{
m_startColor = startColor;
m_endColor = endColor;
update();
}
void GraduateText::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing); //防锯齿
QPainterPath path;
QFont font;
font.setBold(true); //加粗
font.setPixelSize(m_iTextSize); //字体大小
painter.setFont(font);
QFontMetrics fm(font);
int textWidth = fm.width(m_strText);
int textHeight = fm.height();
//文字居中画,注释:文字是从左下角开始画
path.addText(width() / 2 - textWidth / 2, height() / 2 + textHeight / 2, font, m_strText);
QLinearGradient linearGridient(0,height() / 2 - textHeight / 2, 0, height() / 2 + textHeight / 2);
linearGridient.setColorAt(0,m_startColor);
linearGridient.setColorAt(1,m_endColor);
painter.setBrush(linearGridient);
painter.setBrush(linearGridient);
painter.setPen(Qt::NoPen);
painter.drawPath(path);
}
GraduateText w;
w.setText("中国加油!");
w.setTextSize(30);
w.setGraduateColor(Qt::yellow, Qt::red);
w.show();
实现效果: