G
G
Grigory2021-03-16 10:16:54
Qt
Grigory, 2021-03-16 10:16:54

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);
}


when trying to add it to a QFormLayout, its size turned out to be larger than the base widgets. It's like he's got some sort of indentation.
It looks like this:
60505b7ca5a52863254719.png

In the first, everything is collected on layouts, and in the second, a new widget.
The problem feels simple, but I don’t understand what groan to dig into.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Ananiev, 2021-03-16
@Griglapidus

https://doc.qt.io/qt-5/qlayout.html#setContentsMargins

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question