| 1 | // For license of this file, see <project-root-folder>/LICENSE.md. |
| 2 | |
| 3 | #include "gui/reusable/colortoolbutton.h" |
| 4 | |
| 5 | #include "miscellaneous/textfactory.h" |
| 6 | |
| 7 | #include <QColorDialog> |
| 8 | #include <QMouseEvent> |
| 9 | #include <QPainter> |
| 10 | #include <QPainterPath> |
| 11 | #include <QRandomGenerator> |
| 12 | |
| 13 | ColorToolButton::ColorToolButton(QWidget* parent) : QToolButton(parent), m_color(Qt::GlobalColor::black) { |
| 14 | setToolTip(tr("Click me to change color!")); |
| 15 | |
| 16 | connect(this, &ColorToolButton::clicked, this, [this]() { |
| 17 | auto new_color = QColorDialog::getColor(m_color, |
| 18 | parentWidget(), |
| 19 | tr("Select new color"), |
| 20 | QColorDialog::ColorDialogOption::DontUseNativeDialog | |
| 21 | QColorDialog::ColorDialogOption::ShowAlphaChannel); |
| 22 | |
| 23 | if (new_color.isValid()) { |
| 24 | setColor(new_color); |
| 25 | } |
| 26 | }); |
| 27 | } |
| 28 | |
| 29 | QColor ColorToolButton::color() const { |
| 30 | return m_color; |
| 31 | } |
| 32 | |
| 33 | void ColorToolButton::setColor(const QColor& color, bool inform_about_changes) { |
| 34 | m_color = color; |
| 35 | repaint(); |
| 36 | |
| 37 | if (inform_about_changes) { |
| 38 | emit colorChanged(m_color); |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | void ColorToolButton::setRandomColor() { |
| 43 | auto clr = TextFactory::generateRandomColor(); |
| 44 | |
| 45 | setColor(clr); |
| 46 | } |
| 47 | |
| 48 | void ColorToolButton::paintEvent(QPaintEvent* e) { |
| 49 | Q_UNUSED(e) |
| 50 | QPainter p(this); |
| 51 | QRect rect(QPoint(0, 0), size()); |
| 52 | |
| 53 | if (isEnabled()) { |
| 54 | if (underMouse() || isChecked()) { |
| 55 | p.setOpacity(0.7); |
| 56 | } |
| 57 | } |
| 58 | else { |
| 59 | p.setOpacity(0.3); |
| 60 | } |
| 61 | |
| 62 | QPainterPath path; |
| 63 | |
| 64 | path.addRoundedRect(QRectF(rect), 3, 3); |
| 65 | p.fillPath(path, m_color); |
| 66 | } |
| 67 | |
| 68 | QColor ColorToolButton::alternateColor() const { |
| 69 | return m_alternateColor; |
| 70 | } |
| 71 | |
| 72 | void ColorToolButton::setAlternateColor(const QColor& alt_color) { |
| 73 | m_alternateColor = alt_color; |
| 74 | } |
| 75 | |
| 76 | void ColorToolButton::mouseReleaseEvent(QMouseEvent* event) { |
| 77 | QToolButton::mouseReleaseEvent(event); |
| 78 | |
| 79 | if (event->button() == Qt::MouseButton::RightButton) { |
| 80 | setColor(m_alternateColor); |
| 81 | } |
| 82 | } |