Qt Utilities  5.10.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 
20  : QSpinBox(parent)
21  , ButtonOverlay(this)
22  , m_minimumHidden(false)
23 {
24  const QMargins margins = contentsMargins();
25  QStyleOptionComboBox opt;
26  opt.initFrom(this);
27  const int frameWidth = style()->pixelMetric(QStyle::PM_SpinBoxFrameWidth, &opt, this);
28  const int pad = 5;
29  const int buttonWidth = style()->subControlRect(QStyle::CC_SpinBox, &opt, QStyle::SC_SpinBoxUp, this).width() + 10;
30  buttonLayout()->setContentsMargins(margins.left() + frameWidth + pad, margins.top() + frameWidth,
31  margins.right() + frameWidth + pad + buttonWidth, margins.bottom() + frameWidth);
33  connect(this, static_cast<void (ClearSpinBox::*)(int)>(&ClearSpinBox::valueChanged), this, &ClearSpinBox::handleValueChanged);
34 }
35 
40 {
41 }
42 
46 void ClearSpinBox::handleValueChanged(int value)
47 {
48  updateClearButtonVisibility(value != minimum());
49 }
50 
51 void ClearSpinBox::handleClearButtonClicked()
52 {
53  setValue(minimum());
54 }
55 
56 bool ClearSpinBox::isCleared() const
57 {
58  return value() == minimum();
59 }
60 
61 int ClearSpinBox::valueFromText(const QString &text) const
62 {
63  if (m_minimumHidden && text.isEmpty()) {
64  return minimum();
65  } else {
66  return QSpinBox::valueFromText(text);
67  }
68 }
69 
70 QString ClearSpinBox::textFromValue(int val) const
71 {
72  if (m_minimumHidden && (val == minimum())) {
73  return QString();
74  } else {
75  return QSpinBox::textFromValue(val);
76  }
77 }
78 } // namespace Widgets
~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:50
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