summaryrefslogtreecommitdiff
path: root/src/charts/PieRound.cpp
blob: f90d740c4b6067146c856bebe1eaf7ec6ab0c410 (plain)
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
#include "PieRound.h"
#include "PieChartScene.h"

PieRound::PieRound(const QPointF& center, const PieChartScene* scene):
    scene(scene)
{
    setPos(center);
    calculateSum();
    addSectors();
}

QRectF PieRound::boundingRect() const
{
    return QRectF(-Radius, -Radius, 2 * Radius, 2 * Radius);
}

void PieRound::calculateSum()
{
    sum = 0;
    foreach(DataPoint point, scene->getDataSet())
        sum += point.value;
}

void PieRound::addSectors()
{
    qreal angle = -90;
    for(int i = 0; i < scene->getDataSet().size(); i++)
    {
        qreal sweep = 360. * scene->getDataSet()[i].value / sum;
        addSector(i, angle, sweep);
        angle += sweep;
    }
}

void PieRound::addSector(int index, qreal startAngle, qreal sweep)
{
    addSectorItem(createSectorPath(startAngle, sweep),
            QColor(scene->getColors()[index]));
    addSectorLabel(index, startAngle, sweep);
}

QPainterPath PieRound::createSectorPath(qreal startAngle, qreal sweep)
{
    QPainterPath sectorPath;
    sectorPath.arcTo(boundingRect(), -startAngle, -sweep);
    sectorPath.lineTo(QPointF());
    return sectorPath;
}

void PieRound::addSectorItem(const QPainterPath& path, QColor color)
{
    QGraphicsPathItem* sectorItem = new QGraphicsPathItem(path, this);
    sectorItem->setPen(QColor("white"));
    sectorItem->setBrush(color);
}

void PieRound::addSectorLabel(int index, qreal startAngle, qreal sweep)
{
    int value = scene->getDataSet()[index].value;
    if(value == 0)
        return;
    QGraphicsSimpleTextItem* labelItem =
            new QGraphicsSimpleTextItem(QString::number(value), this);
    labelItem->setPos(getLabelPos(startAngle, sweep, labelItem));
}

QPointF PieRound::getLabelPos(qreal startAngle, qreal sweep,
        QGraphicsSimpleTextItem* labelItem)
{
    int radius = sweep > 30 ? LabelRadius : 2 * LabelRadius;
    QRectF labelArcRect(-radius, -radius, 2 * radius, 2 * radius);
    QPainterPath path;
    path.arcMoveTo(labelArcRect, -startAngle - sweep / 2);
    QSizeF labelSize = labelItem->boundingRect().size();
    return path.currentPosition() -
            QPointF(labelSize.width() / 2, labelSize.height() / 2);
}