circulargauge.cpp 1.92 KB
#include "circulargauge.h"

#include <QPainter>
#include <QtDebug>

CircularGauge::CircularGauge(QWidget *parent) : QWidget(parent),
    value(30), maximum(40), minimum(0)
{
    background.load(":/images/gauge/circle_background.png");
}

void CircularGauge::setValue(int value)
{
    value = qBound(minimum, value, maximum);
    if (this->value != value)
    {
        this->value = value;
        update();
    }
}

void CircularGauge::setMaximum(int maximum)
{
    maximum = qMax(minimum, maximum);
    if (this->maximum != maximum)
    {
        this->maximum = maximum;
        update();
    }
}

void CircularGauge::setMinimum(int minimum)
{
    minimum = qMin(minimum, maximum);
    if (this->minimum != minimum)
    {
        this->minimum = minimum;
        update();
    }
}

void CircularGauge::paintEvent(QPaintEvent */*event*/)
{
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.drawImage(0, 0, background);

    painter.save();

    QRect rect((349-339)/2, (348-338)/2, 339, 338);

    qreal degree = (qreal) qMax(value - minimum, 0) / qMax(maximum - minimum, 1) * 345;

    QBrush barBrush(bar);
    barBrush.setTransform(QTransform().translate(5, 5));

    painter.setPen(Qt::NoPen);
    painter.setBrush(barBrush);
    painter.drawPie(rect, 5760 / 4 - 10 * 16, (int) (degree * 16) + 10 * 16 );

    painter.restore();
    painter.save();

    rect = QRect((349-30)/2 + 2, 2, indicator.size().width() - 2, indicator.size().height() - 2);
    rect.translate(-size().width() / 2, -size().height() / 2);

    painter.translate(size().width() / 2, size().height() / 2);
    painter.rotate(-degree);

    painter.drawImage(rect, indicator);

    painter.restore();

    QPen white(Qt::white);
    white.setWidth(3);

    painter.setPen(white);
    painter.drawLine(64.8, 200.4, 285.6, 200.4);

    rect.setSize(icon.size());
    rect.moveCenter(QPoint(349.2/2, 348/3 + 18));

    painter.drawImage(rect, icon);
}