Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
stenzek
GitHub Repository: stenzek/duckstation
Path: blob/master/src/duckstation-qt/colorpickerbutton.cpp
7447 views
1
// SPDX-FileCopyrightText: 2019-2026 Connor McLaughlin <[email protected]>
2
// SPDX-License-Identifier: CC-BY-NC-ND-4.0
3
4
#include "colorpickerbutton.h"
5
6
#include <QtGui/QPainter>
7
#include <QtWidgets/QColorDialog>
8
#include <QtWidgets/QStyle>
9
#include <QtWidgets/QStyleOptionButton>
10
11
#include "moc_colorpickerbutton.cpp"
12
13
ColorPickerButton::ColorPickerButton(QWidget* parent) : QPushButton(parent)
14
{
15
connect(this, &QPushButton::clicked, this, &ColorPickerButton::onClicked);
16
}
17
18
u32 ColorPickerButton::color()
19
{
20
return m_color;
21
}
22
23
void ColorPickerButton::setColor(u32 rgb)
24
{
25
if (m_color == rgb)
26
return;
27
28
m_color = rgb;
29
update();
30
}
31
32
void ColorPickerButton::paintEvent(QPaintEvent* event)
33
{
34
Q_UNUSED(event);
35
36
QPainter painter(this);
37
QStyleOptionButton option;
38
option.initFrom(this);
39
40
if (isDown())
41
option.state |= QStyle::State_Sunken;
42
if (isDefault())
43
option.features |= QStyleOptionButton::DefaultButton;
44
45
// Get the content rect (area inside the border)
46
const QRect contentRect = style()->subElementRect(QStyle::SE_PushButtonContents, &option, this);
47
48
// Draw the button frame first (this includes the border but should not fill the interior)
49
style()->drawPrimitive(QStyle::PE_PanelButtonBevel, &option, &painter, this);
50
51
// Fill the content area with our custom color
52
painter.fillRect(contentRect, QColor::fromRgb(m_color));
53
54
// Draw the focus rectangle if needed
55
if (option.state & QStyle::State_HasFocus)
56
{
57
QStyleOptionFocusRect focusOption;
58
focusOption.initFrom(this);
59
focusOption.rect = style()->subElementRect(QStyle::SE_PushButtonFocusRect, &option, this);
60
style()->drawPrimitive(QStyle::PE_FrameFocusRect, &focusOption, &painter, this);
61
}
62
63
// Draw the button label (text/icon) on top
64
style()->drawControl(QStyle::CE_PushButtonLabel, &option, &painter, this);
65
}
66
67
void ColorPickerButton::onClicked()
68
{
69
const u32 red = (m_color >> 16) & 0xff;
70
const u32 green = (m_color >> 8) & 0xff;
71
const u32 blue = m_color & 0xff;
72
73
const QColor initial(QColor::fromRgb(red, green, blue));
74
const QColor selected(QColorDialog::getColor(initial, this, tr("Select LED Color")));
75
76
// QColorDialog returns Invalid on cancel, and apparently initial == Invalid is true...
77
if (!selected.isValid() || initial == selected)
78
return;
79
80
const u32 new_rgb = (static_cast<u32>(selected.red()) << 16) | (static_cast<u32>(selected.green()) << 8) |
81
static_cast<u32>(selected.blue());
82
m_color = new_rgb;
83
update();
84
emit colorChanged(new_rgb);
85
}
86
87