-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbattery.cpp
More file actions
112 lines (86 loc) · 2.02 KB
/
battery.cpp
File metadata and controls
112 lines (86 loc) · 2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#include "battery.h"
#include <QPainter>
#include <QPainterPath>
Battery::Battery(QWidget *parent)
: QWidget(parent), _value(30)
{
init();
}
void Battery::start()
{
connect(_t, &QTimer::timeout, this, &Battery::refresh);
_t->setInterval(1000);
_t->start();
}
void Battery::setValue(int v)
{
_ani->setStartValue(_value);
_ani->setEndValue(v);
_ani->start();
_value = v;
}
void Battery::setColor(const QColor &bgColor)
{
_bgColor = bgColor;
}
void Battery::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event)
QPainter p(this);
p.setRenderHint(QPainter::Antialiasing, true);
drawBorder(&p);
drawCapacity(&p);
drawText(&p);
}
void Battery::init()
{
_t = new QTimer(this);
_ani = new QPropertyAnimation(this, "_value");
_ani->setDuration(500);
_ani->setEasingCurve(QEasingCurve::OutQuad);
}
void Battery::drawBorder(QPainter *p)
{
p->save();
int w1 = static_cast<int>(width()*0.2);
int h1 = static_cast<int>(height()*0.8);
QPen pen;
pen.setColor(Qt::gray);
pen.setWidth(3);
p->setPen(pen);
p->drawRect(5, 5, width()-10, h1);
p->drawRect(w1, h1+6, static_cast<int>(width()*0.6-10), static_cast<int>(height()*0.1-10));
p->restore();
}
void Battery::drawCapacity(QPainter *p)
{
p->save();
int h = static_cast<int>(height()*0.8 * _value / 100);
QBrush brush(_bgColor);
p->setBrush(brush);
p->drawRect(5, 5, width()-10, h);
p->restore();
}
void Battery::drawText(QPainter *p)
{
p->save();
int w1 = static_cast<int>(width()*0.2);
int h1 = static_cast<int>(height()*0.8);
QPen pen;
pen.setColor(Qt::blue);
p->setPen(pen);
QFont font("楷体", 24, 5);
p->setFont(font);
p->drawText(QRect(w1, h1+6, static_cast<int>(width()*0.6-10), static_cast<int>(height()*0.1-10)), Qt::AlignCenter, QString::number(_value).append("%"));
p->restore();
}
void Battery::_setValue(int v)
{
_value = v;
repaint();
}
void Battery::refresh()
{
setValue(qrand() % 100);
repaint();
}