#include "QBreathingLight.h" #include #include #include QBreathingLight::QBreathingLight(QWidget *parent) : QWidget(parent) , m_opacity(1.0f) , m_isFlashing(false) , m_flashColor(Qt::red) , m_flashDuration(3000) // 默认闪烁3秒 { // 设置固定大小 setFixedSize(40, 40); // 连接定时器信号槽 connect(&m_animationTimer, &QTimer::timeout, this, &QBreathingLight::updateAnimation); } void QBreathingLight::setFlashDuration(int milliseconds) { m_flashDuration = milliseconds; } void QBreathingLight::setFlashColor(const QColor &color) { m_flashColor = color; } void QBreathingLight::triggerSignal() { if (!m_isFlashing) { m_isFlashing = true; m_flashStartTime = QTime::currentTime(); m_animationTimer.start(30); // 30ms更新一次 } } void QBreathingLight::paintEvent(QPaintEvent *event) { Q_UNUSED(event); QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing); // 绘制背景 painter.fillRect(rect(), QBrush(QColor(240, 240, 240))); // 计算中心点 QPoint center = rect().center(); int radius = qMin(width(), height()) / 3; // 根据状态设置颜色 QColor color; if (m_isFlashing) { color = m_flashColor; color.setAlphaF(m_opacity); } else { color = Qt::green; // 未激活状态显示灰色 } // 绘制呼吸灯 painter.setBrush(QBrush(color)); painter.setPen(Qt::NoPen); painter.drawEllipse(center, radius, radius); } void QBreathingLight::updateAnimation() { // 检查是否超过闪烁持续时间 int elapsed = m_flashStartTime.msecsTo(QTime::currentTime()); if (elapsed >= m_flashDuration) { m_isFlashing = false; m_opacity = 1.0f; m_animationTimer.stop(); update(); return; } // 计算呼吸效果 (使用正弦函数实现平滑呼吸效果) float progress = static_cast(elapsed) / m_flashDuration; m_opacity = 0.5f * (1.0f + sin(progress * 2 * 3.14 * 5)); // 每秒闪烁2次 update(); // 触发重绘 }