| 1 | #include "./clearspinbox.h" |
| 2 | |
| 3 | #include <QHBoxLayout> |
| 4 | #include <QStyle> |
| 5 | #include <QStyleOptionSpinBox> |
| 6 | |
| 7 | namespace QtUtilities { |
| 8 | |
| 9 | /*! |
| 10 | * \class ClearSpinBox |
| 11 | * \brief A QSpinBox with an embedded button for clearing its contents and the |
| 12 | * ability to hide |
| 13 | * the minimum value. |
| 14 | */ |
| 15 | |
| 16 | /*! |
| 17 | * \brief Constructs a clear spin box. |
| 18 | */ |
| 19 | ClearSpinBox::ClearSpinBox(QWidget *parent) |
| 20 | : QSpinBox(parent) |
| 21 | , ButtonOverlay(this, lineEdit()) |
| 22 | , m_minimumHidden(false) |
| 23 | { |
| 24 | ButtonOverlay::setClearButtonEnabled(true); |
| 25 | } |
| 26 | |
| 27 | /*! |
| 28 | * \brief Destroys the clear spin box. |
| 29 | */ |
| 30 | ClearSpinBox::~ClearSpinBox() |
| 31 | { |
| 32 | } |
| 33 | |
| 34 | /*! |
| 35 | * \brief Updates the visibility of the clear button. |
| 36 | */ |
| 37 | void ClearSpinBox::handleValueChanged(int value) |
| 38 | { |
| 39 | updateClearButtonVisibility(value != minimum()); |
| 40 | } |
| 41 | |
| 42 | void ClearSpinBox::handleClearButtonClicked() |
| 43 | { |
| 44 | setValue(minimum()); |
| 45 | } |
| 46 | |
| 47 | void ClearSpinBox::handleCustomLayoutCreated() |
| 48 | { |
| 49 | const QStyle *const s = style(); |
| 50 | QStyleOptionSpinBox opt; |
| 51 | opt.initFrom(this); |
| 52 | setContentsMarginsFromEditFieldRectAndFrameWidth( |
| 53 | s->subControlRect(QStyle::CC_SpinBox, &opt, QStyle::SC_SpinBoxEditField, this), s->pixelMetric(QStyle::PM_SpinBoxFrameWidth, &opt, this)); |
| 54 | connect(this, static_cast<void (ClearSpinBox::*)(int)>(&ClearSpinBox::valueChanged), this, &ClearSpinBox::handleValueChanged); |
| 55 | } |
| 56 | |
| 57 | bool ClearSpinBox::isCleared() const |
| 58 | { |
| 59 | return value() == minimum(); |
| 60 | } |
| 61 | |
| 62 | int ClearSpinBox::valueFromText(const QString &text) const |
| 63 | { |
| 64 | if (m_minimumHidden && text.isEmpty()) { |
| 65 | return minimum(); |
| 66 | } else { |
| 67 | return QSpinBox::valueFromText(text); |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | QString ClearSpinBox::textFromValue(int val) const |
| 72 | { |
| 73 | if (m_minimumHidden && (val == minimum())) { |
| 74 | return QString(); |
| 75 | } else { |
| 76 | return QSpinBox::textFromValue(val); |
| 77 | } |
| 78 | } |
| 79 | } // namespace QtUtilities |