widgets/colorbutton.cpp

Sat, 08 Apr 2023 15:03:54 +0300

author
Teemu Piippo <teemu.s.piippo@gmail.com>
date
Sat, 08 Apr 2023 15:03:54 +0300
changeset 344
a24da8de2a3b
parent 264
76a025db4948
child 345
81cd5dee6d77
permissions
-rw-r--r--

Changed color button to a line edit+button combination

#include <QColorDialog>
#include <QStyleFactory>
#include <QHBoxLayout>
#include "widgets/colorbutton.h"

ColorButton::ColorButton(const QColor& color, QWidget* parent) :
	ColorButton{parent}
{
	this->setColor(color);
}

ColorButton::ColorButton(QWidget* parent) :
	QWidget{parent},
	lineEdit{new QLineEdit{this}},
	button{new QPushButton{"…", this}}
{
	auto*const layout = new QHBoxLayout{};
	layout->addWidget(this->lineEdit);
	layout->addWidget(this->button);
	layout->setStretch(0, 1);
	layout->setStretch(1, 0);
	this->setLayout(layout);
	connect(this->button, &QPushButton::clicked, [&](){
		const QColor color = QColorDialog::getColor(this->color(), this->parentWidget());
		if (color.isValid()) {
			this->setColor(color);
		}
	});
	connect(this->lineEdit, &QLineEdit::textChanged, [&]{
		const QColor color = this->color();
		QPalette palette{color};
		const qreal lightness = color.lightnessF();
		const QColor foreground = lightness < 0.4 ? Qt::white : Qt::black;
		const auto style = QStyleFactory::create("Fusion");
		this->setStyle(style);
		this->setStyleSheet(QStringLiteral(
			"*{background-color: %1; color: %2;}"
		).arg(color.name()).arg(foreground.name()));
		/*
		palette.setColor(QPalette::ButtonText, foreground);
		for (QWidget* widget : {(QWidget*)this->lineEdit, (QWidget*)this->button}) {
			widget->setPalette(palette);
			widget->setStyle(style);
		}
		*/
		Q_EMIT this->colorChanged(this->color());
	});
	this->setColor(Qt::black);
}

QColor ColorButton::color() const
{
	return QColor{this->lineEdit->text()};
}

void ColorButton::setColor(const QColor& color)
{
	if (color.isValid() and this->color() != color) {
		this->lineEdit->setText(color.name());
	}
}

mercurial