Answer the question
In order to leave comments, you need to log in
Why is a custom widget larger than its content?
A simple widget for color management has been created:
class ColorInput : public QWidget
{
Q_OBJECT
public:
explicit ColorInput(QWidget *parent = nullptr);
QColor getColor();
QString getColorStr();
signals:
void colorChanged(QColor color);
public slots:
void setColor(QColor color);
void setColor(QString color);
private slots:
void chooseColor();
private:
QColor m_color;
QLineEdit *m_edit = nullptr;
QPushButton *m_btn = nullptr;
};
ColorInput::ColorInput(QWidget *parent) :
QWidget(parent),
m_edit(new QLineEdit(this)),
m_btn(new QPushButton(this))
{
QHBoxLayout *layout = new QHBoxLayout(this);
layout->addWidget(m_edit);
layout->addWidget(m_btn);
setLayout(layout);
m_btn->setIcon(m_btn->style()->standardIcon(QStyle::SP_ArrowLeft));
QObject::connect(m_edit, SIGNAL(textChanged(QString)), this, SLOT(setColor(QString)));
QObject::connect(m_btn, SIGNAL(pressed()), this, SLOT(chooseColor()));
setColor(QString(""));
setBaseSize(200, 20);
}
QColor ColorInput::getColor()
{
return m_color;
}
QString ColorInput::getColorStr()
{
return m_color.name();
}
void ColorInput::setColor(QColor color)
{
m_color = color;
m_edit->setText(m_color.name());
QColor textColor(255 - m_color.red(), 255 - m_color.green(), 255 - m_color.blue());
QSignalBlocker blocker(m_edit);
m_edit->setStyleSheet(QString("color: %1;"
"background-color: %2;"
"selection-color: black;"
"selection-background-color: white;").arg(textColor.name()).arg(m_color.name()));
emit colorChanged(m_color);
}
void ColorInput::setColor(QString color)
{
m_color.setNamedColor(color);
if(!m_color.isValid()) m_color = QColor(Qt::black);
setColor(m_color);
}
void ColorInput::chooseColor()
{
QColor newColor = QColorDialog::getColor(m_color, this, "Выбор цвета");
if(newColor != m_color) setColor(newColor);
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question