all repos — mgba @ 639c0bf0e9499870d122e1579184a99f3f8561cd

mGBA Game Boy Advance Emulator

src/platform/qt/ColorPicker.cpp (view raw)

 1/* Copyright (c) 2013-2017 Jeffrey Pfau
 2 *
 3 * This Source Code Form is subject to the terms of the Mozilla Public
 4 * License, v. 2.0. If a copy of the MPL was not distributed with this
 5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 6#include "ColorPicker.h"
 7
 8#include <QColorDialog>
 9#include <QEvent>
10
11using namespace QGBA;
12
13ColorPicker::ColorPicker() {
14}
15
16ColorPicker::ColorPicker(QWidget* parent, const QColor& defaultColor)
17	: m_parent(parent)
18	, m_defaultColor(defaultColor)
19{
20	QPalette palette = parent->palette();
21	palette.setColor(parent->backgroundRole(), defaultColor);
22	parent->setPalette(palette);
23	parent->installEventFilter(this);
24}
25
26ColorPicker& ColorPicker::operator=(const ColorPicker& other) {
27	if (m_parent) {
28		m_parent->removeEventFilter(this);
29	}
30	m_parent = other.m_parent;
31	m_defaultColor = other.m_defaultColor;
32	m_parent->installEventFilter(this);
33
34	return *this;
35}
36
37void ColorPicker::setColor(const QColor& color) {
38	m_defaultColor = color;
39
40	QPalette palette = m_parent->palette();
41	palette.setColor(m_parent->backgroundRole(), color);
42	m_parent->setPalette(palette);
43}
44
45bool ColorPicker::eventFilter(QObject* obj, QEvent* event) {
46	if (event->type() != QEvent::MouseButtonRelease) {
47		return false;
48	}
49	if (obj != m_parent) {
50		return false;
51	}
52
53	QWidget* swatch = static_cast<QWidget*>(obj);
54
55	QColorDialog* colorPicker = new QColorDialog;
56	colorPicker->setAttribute(Qt::WA_DeleteOnClose);
57	colorPicker->setCurrentColor(m_defaultColor);
58	colorPicker->open();
59	connect(colorPicker, &QColorDialog::colorSelected, [this, swatch](const QColor& color) {
60		m_defaultColor = color;
61		QPalette palette = swatch->palette();
62		palette.setColor(swatch->backgroundRole(), color);
63		swatch->setPalette(palette);
64		emit colorChanged(color);
65	});
66	return true;
67}