widgets/coloredit.cpp

changeset 348
98776f54a8d0
parent 347
5c655cc006de
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/widgets/coloredit.cpp	Sat Apr 08 15:15:20 2023 +0300
@@ -0,0 +1,51 @@
+#include <QColorDialog>
+#include <QHBoxLayout>
+#include "widgets/coloredit.h"
+
+ColorEdit::ColorEdit(const QColor& color, QWidget* parent) :
+	ColorEdit{parent}
+{
+	this->setColor(color);
+}
+
+ColorEdit::ColorEdit(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();
+		const qreal lightness = color.lightnessF();
+		const QColor foreground = lightness < 0.4 ? Qt::white : Qt::black;
+		this->setStyleSheet(
+			QStringLiteral("QLineEdit{background-color: %1; color: %2;}")
+				.arg(color.name())
+				.arg(foreground.name()));
+		Q_EMIT this->colorChanged(this->color());
+	});
+	this->setColor(Qt::black);
+}
+
+QColor ColorEdit::color() const
+{
+	return QColor{this->lineEdit->text()};
+}
+
+void ColorEdit::setColor(const QColor& color)
+{
+	if (color.isValid() and this->color() != color) {
+		this->lineEdit->setText(color.name());
+	}
+}

mercurial