|
| 1 | +#include "wigglywidget.h" |
| 2 | + |
| 3 | +#include <QFontMetrics> |
| 4 | +#include <QPainter> |
| 5 | +#include <QTimerEvent> |
| 6 | + |
| 7 | +WigglyWidget::WigglyWidget(QWidget *parent) : QWidget(parent), step(0) { |
| 8 | + setBackgroundRole(QPalette::Midlight); |
| 9 | + setAutoFillBackground(true); |
| 10 | + |
| 11 | + QFont newFont = font(); |
| 12 | + newFont.setPointSize(newFont.pointSize() + 20); |
| 13 | + setFont(newFont); |
| 14 | + |
| 15 | + timer.start(60, this); |
| 16 | +} |
| 17 | + |
| 18 | +void WigglyWidget::setText(const QString &newText) { text = newText; } |
| 19 | + |
| 20 | +void WigglyWidget::paintEvent(QPaintEvent * /* event */) |
| 21 | + |
| 22 | +{ |
| 23 | + static constexpr int sineTable[16] = {0, 38, 71, 92, 100, 92, 71, 38, |
| 24 | + 0, -38, -71, -92, -100, -92, -71, -38}; |
| 25 | + |
| 26 | + QFontMetrics metrics(font()); |
| 27 | + int x = (width() - metrics.horizontalAdvance(text)) / 2; |
| 28 | + int y = (height() + metrics.ascent() - metrics.descent()) / 2; |
| 29 | + QColor color; |
| 30 | + |
| 31 | + QPainter painter(this); |
| 32 | + |
| 33 | + for (int i = 0; i < text.size(); ++i) { |
| 34 | + int index = (step + i) % 16; |
| 35 | + color.setHsv((15 - index) * 16, 255, 191); |
| 36 | + painter.setPen(color); |
| 37 | + painter.drawText(x, y - ((sineTable[index] * metrics.height()) / 400), |
| 38 | + QString(text[i])); |
| 39 | + x += metrics.horizontalAdvance(text[i]); |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +void WigglyWidget::timerEvent(QTimerEvent *event) { |
| 44 | + if (event->timerId() == timer.timerId()) { |
| 45 | + ++step; |
| 46 | + update(); |
| 47 | + } else { |
| 48 | + QWidget::timerEvent(event); |
| 49 | + } |
| 50 | +} |
0 commit comments