#include <QPainter>
#include <QTimerEvent>
#include <QFont>
#include <QLabel>
#include <QPropertyAnimation>
#include <QGraphicsOpacityEffect>
#include "BannerWidget.h"
BannerWidget::BannerWidget(QWidget *parent)
: QWidget(parent),
m_nStep(0)
{
setAutoFillBackground(true);
m_strText = QString::fromLocal8Bit("Good my dear student");
// 设置文字大小
QFont newFont = font();
newFont.setPointSize(newFont.pointSize() + 20);
setFont(newFont);
m_timer.start(100, this);
QLabel *label = new QLabel(this);
label->resize(200, 200);
label->setStyleSheet("background-color:qlineargradient(spread:pad,x1:0, y1:0, x2:1, y2:0,stop:0 #030303,stop:0.5 #030303 ,stop:1 #2E8B57)"); /* 创建一个动画对象 */
QPropertyAnimation *animation = new QPropertyAnimation(label);
/* 设置动画目标 */
animation->setTargetObject(label);
/* 设置窗口的位置作为动画参考 */
animation->setPropertyName("pos");
/* 设置动画持续时长 */
animation->setDuration(1000);
/* 设置动画开始位置 */
animation->setStartValue(QPoint(20, 45));
/* 设置动画结束位置 */
animation->setEndValue(QPoint(200, 45));
/* 设置循环次数:-1为无限次 */
animation->setLoopCount(-1);
/* 开始动画 */
animation->start();
}
BannerWidget::~BannerWidget()
{
m_timer.stop();
}
void BannerWidget::setText(const QString &text)
{
m_strText = text;
}
void BannerWidget::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event);
QPainter painter(this);
//painter.setCompositionMode( QPainter::CompositionMode_Clear );
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setBrush(QBrush(QColor("#ededed")));
painter.drawRect(50, 50, 200, 200);
}
void BannerWidget::timerEvent(QTimerEvent *event)
{
Q_UNUSED(event);
if (event->timerId() == m_timer.timerId())
{
m_nStep--;
update();
}
else
{
QWidget::timerEvent(event);
}
}
首先,设置一个中间白色、两边灰色的渐变背景色;
其次,文字填充颜色设为透明(才能看到白色背景);
接着,把文字之外的背景色给裁剪掉(只显示文字);
https://blog.youkuaiyun.com/weixin_32819955/article/details/119374274