preheattempgauge.cpp 1.7 KB
#include "preheattempgauge.h"

#include <QPainter>
#include <QtDebug>

PreheatTempGauge::PreheatTempGauge(QWidget *parent) : QWidget(parent)
{
    border.load(":/images/gauge/bar_short_frame.png");
    indicator.load(":/images/gauge/bar_indicator.png");
    body.load(":/images/gauge/bar_short_red.png");

    val = 0;
    min = 0;
    max = 1;
}

void PreheatTempGauge::setValue(int value)
{
    if (value == val)
        return;

    val = qBound(min, value, max);

    update();
}

void PreheatTempGauge::setMinimum(int minimum)
{
    if (minimum == min)
        return;

    min = minimum;
    max = qMax(min, max);
    val = qBound(min, val, max);

    update();
}

void PreheatTempGauge::setMaximum(int maximum)
{
    if (maximum == max)
        return;

    max = maximum;
    min = qMin(min, max);
    val = qBound(min, val, max);

    update();
}

void PreheatTempGauge::paintEvent(QPaintEvent */*event*/)
{
    QPainter painter(this);
    painter.setBrush(Qt::NoBrush);
    painter.setPen(Qt::NoPen);

    qreal percentage = (qreal) (val - min) / qMax(max - min, 1);
    percentage = qBound((qreal) 0.0, percentage, (qreal) 1.0);

    QRect targetRect(
                (border.size().width() - body.size().width()) / 2 + indicator.size().width() / 2,
                (border.size().height() - body.size().height()) / 2 + indicator.size().height(),
                body.size().width() * percentage, body.height());

    QRect sourceRect(0, 0, body.size().width() * percentage, body.height());

    painter.drawPixmap(targetRect, body, sourceRect);
    painter.drawPixmap(indicator.size().width() / 2, indicator.size().height(), border);
    painter.drawPixmap(targetRect.right() - indicator.size().width() / 2, 0, indicator);
}