widgets/colorbutton.cpp

changeset 348
98776f54a8d0
parent 347
5c655cc006de
child 349
673b8dffbe14
equal deleted inserted replaced
347:5c655cc006de 348:98776f54a8d0
1 #include <QColorDialog>
2 #include <QHBoxLayout>
3 #include "widgets/colorbutton.h"
4
5 ColorEdit::ColorEdit(const QColor& color, QWidget* parent) :
6 ColorEdit{parent}
7 {
8 this->setColor(color);
9 }
10
11 ColorEdit::ColorEdit(QWidget* parent) :
12 QWidget{parent},
13 lineEdit{new QLineEdit{this}},
14 button{new QPushButton{"…", this}}
15 {
16 auto*const layout = new QHBoxLayout{};
17 layout->addWidget(this->lineEdit);
18 layout->addWidget(this->button);
19 layout->setStretch(0, 1);
20 layout->setStretch(1, 0);
21 this->setLayout(layout);
22 connect(this->button, &QPushButton::clicked, [&](){
23 const QColor color = QColorDialog::getColor(this->color(), this->parentWidget());
24 if (color.isValid()) {
25 this->setColor(color);
26 }
27 });
28 connect(this->lineEdit, &QLineEdit::textChanged, [&]{
29 const QColor color = this->color();
30 const qreal lightness = color.lightnessF();
31 const QColor foreground = lightness < 0.4 ? Qt::white : Qt::black;
32 this->setStyleSheet(
33 QStringLiteral("QLineEdit{background-color: %1; color: %2;}")
34 .arg(color.name())
35 .arg(foreground.name()));
36 Q_EMIT this->colorChanged(this->color());
37 });
38 this->setColor(Qt::black);
39 }
40
41 QColor ColorEdit::color() const
42 {
43 return QColor{this->lineEdit->text()};
44 }
45
46 void ColorEdit::setColor(const QColor& color)
47 {
48 if (color.isValid() and this->color() != color) {
49 this->lineEdit->setText(color.name());
50 }
51 }

mercurial