1 // Copyright (C) 2012-2019 The VPaint Developers.
2 // See the COPYRIGHT file at the top-level directory of this distribution
3 // and at https://github.com/dalboris/vpaint/blob/master/COPYRIGHT
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 // http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16
17 #include "ColorSelector.h"
18 #include <QColorDialog>
19 #include <QPainter>
20
ColorSelector(const Color & initialColor,QWidget * parent)21 ColorSelector::ColorSelector(const Color & initialColor, QWidget *parent) :
22 QToolButton(parent),
23 color_(initialColor)
24 {
25 connect(this, SIGNAL(clicked()), this, SLOT(processClick_()));
26 updateIcon();
27 setFocusPolicy(Qt::NoFocus);
28 }
29
color() const30 Color ColorSelector::color() const
31 {
32 return color_;
33 }
34
setColor(const Color & newColor)35 void ColorSelector::setColor(const Color & newColor)
36 {
37 if (newColor.isValid())
38 {
39 color_ = newColor;
40 updateIcon();
41 emit colorChanged(color_);
42 }
43 }
44
processClick_()45 void ColorSelector::processClick_()
46 {
47 Color c = QColorDialog::getColor(
48 color_,
49 0,
50 tr("select the color"),
51 QColorDialog::ShowAlphaChannel);
52
53 setColor(c);
54 }
55
updateIcon()56 void ColorSelector::updateIcon()
57 {
58 // Compute text color depending on background color
59 QColor textColor(0,0,0);
60 if(color_.lightnessF() < 0.5)
61 textColor = QColor(255,255,255);
62
63 // Get icon size
64 QSize pixSize = iconSize();
65 int w = pixSize.width();
66 int h = pixSize.height();
67
68 // Create icon
69 QPixmap checkerboard(":/images/checkerboard.png"), pix(pixSize);
70 //checkerboard.brush(color_);
71 QPainter painter(&pix);
72 QRect r(0,0,w-1,h-1);
73 painter.fillRect(r, QBrush(checkerboard));
74 painter.fillRect(r, QBrush(color_));
75
76 // Border
77 painter.setPen(QPen(Qt::black));
78 painter.drawRect(r);
79
80 // Text
81 painter.setPen(QPen(textColor));
82 painter.setFont(QFont("Arial"));
83 painter.drawText(0, 0, w, h, (Qt::AlignHCenter | Qt::AlignVCenter), text());
84
85 // Set pixmap as tool icon
86 setIcon(pix);
87 }
88
89