QDoubleValidator can only be used as a comma, as a separator between the fractional and integer parts. The number read further from linedith is accordingly not perceived as double . How to replace a comma with a period?
|
3 answers
The validate method of the QValidator class QValidator virtual. Why not take advantage of this to extend the QDoubleValidator :
#include <QCoreApplication> #include <QDoubleValidator> #include <QString> #include <QStringList> #include <QDebug> class CustomValiudator : public QDoubleValidator{ QStringList _decimalPoints; public: CustomValiudator(){ _decimalPoints.append("."); _decimalPoints.append(","); _decimalPoints.append("comma"); } State validate(QString &str, int &pos) const{ QString s(str); for(QStringList::ConstIterator point = _decimalPoints.begin(); point != _decimalPoints.end(); ++point){ s.replace(*point, locale().decimalPoint()); } return QDoubleValidator::validate(s, pos); } }; int main(int argc, char *argv[]){ QCoreApplication a(argc, argv); CustomValiudator v; QString str("123"); int pos = 0; qDebug() << v.validate(str, pos); //2 -> QValidator::Acceptable str = "123.4"; qDebug() << v.validate(str, pos); //2 -> QValidator::Acceptable str = "123comma4"; qDebug() << v.validate(str, pos); //2 -> QValidator::Acceptable return a.exec(); } The bottom line is that we replace all the separators that we need with the separator that QDoubleValidator arranges.
- thank. I immediately apologize for the stupid question, but how can I see the code for the validate function defined for the QDoubleValidator class? After all, you first looked at how it was written for him to override for CustomValiudator, if I understand correctly - bronstein87
- @ bronstein87, no, I paid help. If you really want to see the code, I use debugger. I got the validator
C:\Qt\4.8.6\src\gui\widgets\qvalidator.cppinC:\Qt\4.8.6\src\gui\widgets\qvalidator.cpp- yrHeTaTeJlb
|
You can set the validator to the English locale, in which the delimiter is a period
QLocale locale(QLocale::Englishs); validator->setLocale(locale); |
Perhaps so.
lineEdit->setValidator(new QRegExpValidator(QRegExp("[-]{0,1}\d{0,}\.\d{0,}"),0) ); - I’m kind of asked about QDoubleValidator, I can do validators with regular expressions - bronstein87
- Then feel free to use a regular expression. - Dmitry Petukhov pm
- Well, that's all clear. In this case, you want to say that it is not possible to replace the delimiter in QDoubleValidator with a dot? - bronstein87
- As far as I know, no. - Dmitry Petukhov 6:36 pm
- I just asked what, I also need to set the range of possible values, and the setRange method that belongs to QDoubleValidator is perfect for this, and I don’t know how to set ranges with regular expressions. - bronstein87
|