Qt Utilities  5.6.0
Common Qt related C++ classes and routines used by my applications such as dialogs, widgets and models
clearspinbox.cpp
Go to the documentation of this file.
1 #include "./clearspinbox.h"
2 
3 #include <QHBoxLayout>
4 #include <QStyle>
5 #include <QStyleOptionSpinBox>
6 
7 namespace Widgets {
8 
18 ClearSpinBox::ClearSpinBox(QWidget *parent) :
19  QSpinBox(parent),
20  ButtonOverlay(this),
21  m_minimumHidden(false)
22 {
23  const QMargins margins = contentsMargins();
24  QStyleOptionComboBox opt;
25  opt.initFrom(this);
26  const int frameWidth = style()->pixelMetric(QStyle::PM_SpinBoxFrameWidth, &opt, this);
27  const int pad = 5;
28  const int buttonWidth = style()->subControlRect(QStyle::CC_SpinBox, &opt, QStyle::SC_SpinBoxUp, this).width() + 10;
29  buttonLayout()->setContentsMargins(margins.left() + frameWidth + pad, margins.top() + frameWidth, margins.right() + frameWidth + pad + buttonWidth, margins.bottom() + frameWidth);
31  connect(this, static_cast<void (ClearSpinBox::*)(int)>(&ClearSpinBox::valueChanged), this, &ClearSpinBox::handleValueChanged);
32 }
33 
38 {}
39 
43 void ClearSpinBox::handleValueChanged(int value)
44 {
45  updateClearButtonVisibility(value != minimum());
46 }
47 
48 void ClearSpinBox::handleClearButtonClicked()
49 {
50  setValue(minimum());
51 }
52 
53 bool ClearSpinBox::isCleared() const
54 {
55  return value() == minimum();
56 }
57 
58 int ClearSpinBox::valueFromText(const QString &text) const
59 {
60  if(m_minimumHidden && text.isEmpty()) {
61  return minimum();
62  } else {
63  return QSpinBox::valueFromText(text);
64  }
65 }
66 
67 QString ClearSpinBox::textFromValue(int val) const
68 {
69  if(m_minimumHidden && (val == minimum())) {
70  return QString();
71  } else {
72  return QSpinBox::textFromValue(val);
73  }
74 }
75 
76 }
~ClearSpinBox()
Destroys the clear spin box.
void updateClearButtonVisibility(bool visible)
Updates the visibility of the clear button.
QHBoxLayout * buttonLayout()
Returns the layout manager holding the buttons.
Definition: buttonoverlay.h:51
ClearSpinBox(QWidget *parent=nullptr)
Constructs a clear spin box.
The ButtonOverlay class is used to display buttons on top of other widgets.
Definition: buttonoverlay.h:17
void setClearButtonEnabled(bool enabled)
Sets whether the clear button is enabled.
Provides a set of extended widgets such as ClearLineEdit and ClearComboBox.
Definition: buttonoverlay.h:13
A QSpinBox with an embedded button for clearing its contents and the ability to hide the minimum valu...
Definition: clearspinbox.h:15
#define text
int valueFromText(const QString &text) const
bool isCleared() const
Returns whether the related widget is cleared.
QString textFromValue(int val) const