qtutilities/widgets/clearspinbox.cpp

80 lines
1.8 KiB
C++
Raw Permalink Normal View History

2015-09-06 20:19:21 +02:00
#include "./clearspinbox.h"
2015-04-22 18:57:44 +02:00
#include <QHBoxLayout>
#include <QStyle>
#include <QStyleOptionSpinBox>
namespace QtUtilities {
2015-04-22 18:57:44 +02:00
/*!
* \class ClearSpinBox
2017-05-04 22:46:37 +02:00
* \brief A QSpinBox with an embedded button for clearing its contents and the
* ability to hide
2015-04-22 18:57:44 +02:00
* the minimum value.
*/
/*!
* \brief Constructs a clear spin box.
*/
2017-05-01 03:16:25 +02:00
ClearSpinBox::ClearSpinBox(QWidget *parent)
: QSpinBox(parent)
, ButtonOverlay(this, lineEdit())
2017-05-01 03:16:25 +02:00
, m_minimumHidden(false)
2015-04-22 18:57:44 +02:00
{
ButtonOverlay::setClearButtonEnabled(true);
2015-04-22 18:57:44 +02:00
}
/*!
* \brief Destroys the clear spin box.
*/
ClearSpinBox::~ClearSpinBox()
2017-05-01 03:16:25 +02:00
{
}
2015-04-22 18:57:44 +02:00
/*!
* \brief Updates the visibility of the clear button.
*/
void ClearSpinBox::handleValueChanged(int value)
{
updateClearButtonVisibility(value != minimum());
}
void ClearSpinBox::handleClearButtonClicked()
{
setValue(minimum());
}
void ClearSpinBox::handleCustomLayoutCreated()
{
const QStyle *const s = style();
QStyleOptionSpinBox opt;
opt.initFrom(this);
setContentsMarginsFromEditFieldRectAndFrameWidth(
s->subControlRect(QStyle::CC_SpinBox, &opt, QStyle::SC_SpinBoxEditField, this), s->pixelMetric(QStyle::PM_SpinBoxFrameWidth, &opt, this));
connect(this, static_cast<void (ClearSpinBox::*)(int)>(&ClearSpinBox::valueChanged), this, &ClearSpinBox::handleValueChanged);
}
2015-04-22 18:57:44 +02:00
bool ClearSpinBox::isCleared() const
{
return value() == minimum();
}
int ClearSpinBox::valueFromText(const QString &text) const
{
2017-05-01 03:16:25 +02:00
if (m_minimumHidden && text.isEmpty()) {
2015-04-22 18:57:44 +02:00
return minimum();
} else {
return QSpinBox::valueFromText(text);
}
}
QString ClearSpinBox::textFromValue(int val) const
{
2017-05-01 03:16:25 +02:00
if (m_minimumHidden && (val == minimum())) {
2015-04-22 18:57:44 +02:00
return QString();
} else {
return QSpinBox::textFromValue(val);
}
}
} // namespace QtUtilities