Source

pynoto / src / Core / ColorChooser.cpp

Full commit
#include <QDebug>
#include <QPainter>
#include <QColorDialog>
#include <QStyle>
#include <QStyleOptionButton>
#include <QMenu>
#include "ColorChooser.h"

ColorChooser::ColorChooser(QWidget* parent):
    QToolButton(parent)
{
    QMenu * menu = new QMenu(this);
    menu->addAction(tr("Reset"), this, SLOT(colorReset()));
    setMenu(menu);
    setPopupMode(QToolButton::MenuButtonPopup);
    setColor(QColor(0, 0, 0, 0));
    connect(this, SIGNAL(clicked()), SLOT(showDialog()));
}

ColorChooser::~ColorChooser()
{
}

QColor ColorChooser::color()
{
    return _color;
}

void ColorChooser::setColor(QColor color)
{
    _color = color;
    setText(_color.alpha() == 0 ? tr("Transparent") : _color.name().toUpper());
}

bool ColorChooser::isLight()
{
    int yiq = ((_color.red()*299)+(_color.green()*587)+(_color.blue()*114))/1000;
    return yiq >= 128;
}

void ColorChooser::paintEvent(QPaintEvent *evt)
{
    QToolButton::paintEvent(evt);
    if (_color.alpha() != 0){
        QPainter paint(this);
        QStyleOptionButton option;
        option.initFrom(this);
        option.state = isDown() ? QStyle::State_Sunken : QStyle::State_Raised;
        option.text = text();
        option.icon = icon();
        int menuWidth = style()->pixelMetric(QStyle::PM_MenuButtonIndicator, &option, this);
        QRect drawRect = style()->subElementRect(QStyle::SE_PushButtonFocusRect, &option, this).adjusted(2, 0, -2 - menuWidth, -0);
        if (isEnabled()){
            paint.fillRect(drawRect, _color);
        }
        paint.setPen(_color.alpha() == 0 || isLight() ? Qt::black : Qt::white);
        paint.drawText(drawRect, Qt::AlignCenter, text());
    }
}

void ColorChooser::showDialog()
{
    QColorDialog dlg(_color, this);
    if (dlg.exec() == QDialog::Accepted){
        setColor(dlg.currentColor());
        emit changed(_color);
    }
}

QSize ColorChooser::sizeHint()
{
    return QSize(60, 24);
}

void ColorChooser::colorReset()
{
    setColor(Qt::transparent);
}