QT5 compatability fix
[hypercube:hypercube.git] / GUI / colorcombobox.cpp
1 #include <QColorDialog>
2 #include <QPainter>
3 #include "colorcombobox.h"
4
5
6 ColorComboBox::ColorComboBox(QWidget *parent)
7         : QComboBox(parent)
8 {
9         connect(this, SIGNAL(activated(int)), SLOT(emitActivatedColor(int)));
10
11         addItem(tr("More..."));
12
13         addColor(Qt::black, tr("Black"));
14         addColor(Qt::red, tr("Red"));
15         addColor(Qt::green, tr("Green"));
16         addColor(Qt::blue, tr("Blue"));
17
18         lastActivated = Qt::black;
19         setColor(lastActivated);
20 }
21
22 void ColorComboBox::addColor(const QColor &color, const QString &name)
23 {
24         QFontMetrics fm = fontMetrics();
25         int iconSize = fm.height() - 2;
26         QPixmap pix(iconSize, iconSize);
27         QPainter painter(&pix);
28
29         painter.setPen(Qt::gray);
30         painter.setBrush(QBrush(color));
31         painter.drawRect(0, 0, iconSize, iconSize);
32         QIcon icon(pix);
33
34         insertItem(colorCount(), pix, name, color);
35 }
36
37 int ColorComboBox::colorCount() const
38 {
39     return QComboBox::count() - 1;
40 }
41
42 QColor ColorComboBox::color() const
43 {
44         return itemData(currentIndex()).value<QColor>();
45 }
46
47 void ColorComboBox::setColor(const QColor &color)
48 {
49         int index;
50
51         if ((index = findData(color)) >= 0)
52                 setCurrentIndex(index);
53         else {
54                 addColor(color, color.name());
55                 setCurrentIndex(colorCount() - 1);
56         }
57 }
58
59 QSize ColorComboBox::sizeHint() const
60 {
61         QFontMetrics fm = fontMetrics();
62         QStyleOptionComboBox box;
63         box.initFrom(this);
64         return style()->sizeFromContents(QStyle::CT_ComboBox, &box,
65           QSize(fm.width("#000000") + fm.height() + 4, fm.height()), this);
66 }
67
68 void ColorComboBox::emitActivatedColor(int index)
69 {
70         QColor color;
71         int currentIndex;
72
73         if (index == colorCount()) {
74                 color = QColorDialog::getColor();
75
76                 if (color.isValid()) {
77                         if ((currentIndex = findData(color)) < 0) {
78                                 addColor(color, color.name());
79                                 setCurrentIndex(index);
80                         } else {
81                                 setCurrentIndex(currentIndex);
82                         }
83                 } else {
84                         setColor(lastActivated);
85                         color = lastActivated;
86                 }
87         } else
88                 color = itemData(index).value<QColor>();
89
90         update();
91         lastActivated = color;
92         emit activated(color);
93 }