Path: blob/master/src/duckstation-qt/colorpickerbutton.cpp
4802 views
// SPDX-FileCopyrightText: 2019-2025 Connor McLaughlin <[email protected]>1// SPDX-License-Identifier: CC-BY-NC-ND-4.023#include "colorpickerbutton.h"4#include "qtutils.h"56#include <QtGui/QPainter>7#include <QtWidgets/QColorDialog>8#include <QtWidgets/QStyle>9#include <QtWidgets/QStyleOptionButton>1011#include "moc_colorpickerbutton.cpp"1213ColorPickerButton::ColorPickerButton(QWidget* parent) : QPushButton(parent)14{15connect(this, &QPushButton::clicked, this, &ColorPickerButton::onClicked);16}1718u32 ColorPickerButton::color()19{20return m_color;21}2223void ColorPickerButton::setColor(u32 rgb)24{25if (m_color == rgb)26return;2728m_color = rgb;29update();30}3132void ColorPickerButton::paintEvent(QPaintEvent* event)33{34Q_UNUSED(event);3536QPainter painter(this);37QStyleOptionButton option;38option.initFrom(this);3940if (isDown())41option.state |= QStyle::State_Sunken;42if (isDefault())43option.features |= QStyleOptionButton::DefaultButton;4445// Get the content rect (area inside the border)46const QRect contentRect = style()->subElementRect(QStyle::SE_PushButtonContents, &option, this);4748// Draw the button frame first (this includes the border but should not fill the interior)49style()->drawPrimitive(QStyle::PE_PanelButtonBevel, &option, &painter, this);5051// Fill the content area with our custom color52painter.fillRect(contentRect, QColor::fromRgb(m_color));5354// Draw the focus rectangle if needed55if (option.state & QStyle::State_HasFocus)56{57QStyleOptionFocusRect focusOption;58focusOption.initFrom(this);59focusOption.rect = style()->subElementRect(QStyle::SE_PushButtonFocusRect, &option, this);60style()->drawPrimitive(QStyle::PE_FrameFocusRect, &focusOption, &painter, this);61}6263// Draw the button label (text/icon) on top64style()->drawControl(QStyle::CE_PushButtonLabel, &option, &painter, this);65}6667void ColorPickerButton::onClicked()68{69const u32 red = (m_color >> 16) & 0xff;70const u32 green = (m_color >> 8) & 0xff;71const u32 blue = m_color & 0xff;7273const QColor initial(QColor::fromRgb(red, green, blue));74const QColor selected(QColorDialog::getColor(initial, QtUtils::GetRootWidget(this), tr("Select LED Color")));7576// QColorDialog returns Invalid on cancel, and apparently initial == Invalid is true...77if (!selected.isValid() || initial == selected)78return;7980const u32 new_rgb = (static_cast<u32>(selected.red()) << 16) | (static_cast<u32>(selected.green()) << 8) |81static_cast<u32>(selected.blue());82m_color = new_rgb;83update();84emit colorChanged(new_rgb);85}868788