
Originally Posted by
wysota
I think changing the validator is not enough. The spinbox has its own internal validation method - valueFromText. It's enough if you reimplement it and convert the text to double there, no need for a validator.
The problem is just that without altering the validator, one can't type a comma. Here's the solution I ended up with:
{
Q_OBJECT
public:
{
m_decimalSymbol = KGlobal::locale()->monetaryDecimalSymbol();
// regexp for the validator:
// 1) optional minus sign then 0 or more digits
// 2) dot or locale decimal symbol
// 3) 0, 1 or 2 digits
(m_decimalSymbol != "." ? m_decimalSymbol : "") // add locale deciman symbol if it's not a dot
+ "]?[0-9]{,2}"), this));
setAlignment(Qt::AlignRight);
setRange(-9999999999.99, 9999999999.99);
}
private:
double valueFromText
(const QString &text
) const {
QString m_decimalSymbol
= KGlobal
::locale()->monetaryDecimalSymbol
();
temp.
replace(QRegExp(m_decimalSymbol
),
".");
// replace locale decimal symbol with dot before toDouble()
return temp.toDouble();
}
{
// let's *really* trust the validator :-)
}
};
class AmountSpinBox : public QDoubleSpinBox
{
Q_OBJECT
public:
AmountSpinBox(QWidget *parent = 0) : QDoubleSpinBox(parent)
{
m_decimalSymbol = KGlobal::locale()->monetaryDecimalSymbol();
// regexp for the validator:
// 1) optional minus sign then 0 or more digits
// 2) dot or locale decimal symbol
// 3) 0, 1 or 2 digits
lineEdit()->setValidator(new QRegExpValidator(QRegExp("-?[0-9]*[." +
(m_decimalSymbol != "." ? m_decimalSymbol : "") // add locale deciman symbol if it's not a dot
+ "]?[0-9]{,2}"), this));
setAlignment(Qt::AlignRight);
setButtonSymbols(QDoubleSpinBox::PlusMinus);
setRange(-9999999999.99, 9999999999.99);
}
private:
double valueFromText(const QString &text) const
{
QString m_decimalSymbol = KGlobal::locale()->monetaryDecimalSymbol();
QString temp = text;
temp.replace(QRegExp(m_decimalSymbol), "."); // replace locale decimal symbol with dot before toDouble()
return temp.toDouble();
}
QValidator::State validate ( QString & input, int & pos ) const
{
// let's *really* trust the validator :-)
return QValidator::Acceptable;
}
QString m_decimalSymbol;
};
To copy to clipboard, switch view to plain text mode
Bookmarks