c++ - Force QLineEdit to be a collection of double values -
consider problem.
i have qlineedit in tool , should organize support follows. text of lineedit must contain double values, separated comas. f.e. 6.2 , 8, 9.0, 55 must validate, user cannot input other character numbers , comas. should write method convert text vector. thought qregexp , boost::spirit. can hard using these technique.
any ideas?
use next custom validator.
header:
#ifndef validator_h #define validator_h #include <qvalidator> class validator : public qvalidator { q_object public: explicit validator(qobject *parent = 0); signals: public slots: public: qvalidator::state validate(qstring & input, int & pos) const; }; #endif // validator_h
cpp:
#include "validator.h" #include <qdoublevalidator> #include <qdebug> validator::validator(qobject *parent) : qvalidator(parent) { } qvalidator::state validator::validate(qstring &input, int &pos) const { qdebug() << input<< pos; qdoublevalidator val; val.setlocale(qlocale(qlocale::german,qlocale::germany)); input.remove(" "); qstringlist list = input.split(","); foreach ( qstring var, list) { int = 0; if(val.validate(var,i) == qvalidator::invalid) return qvalidator::invalid; } return qvalidator::acceptable; }
usage:
ui->lineedit->setvalidator(new validator);
explanation about: val.setlocale(qlocale(qlocale::german,qlocale::germany));
you said want use 6.2,...
.
, ,
different decimal point in different countries. wrote example accordingly question. german locale think .
correct point.
but recommend use locale-specific decimal point , use purpose ; separator instead of coma.
there mistakes, try this. edit(improved):
qvalidator::state validator::validate(qstring &input, int &pos) const { qdebug() << input<< pos; qregexpvalidator reg(qregexp("[0-9]+(\\.[0-9]+)?$")); input.remove(" "); if(input.contains(",,") || input.startswith(",")) return qvalidator::invalid; qstringlist list = input.split(","); qdebug()<< list; bool isok = true; foreach ( qstring var, list) { int = 0; if(reg.validate(var,i) == qvalidator::invalid) return qvalidator::invalid; if(reg.validate(var,i) == qvalidator::intermediate) isok = false; } if(isok) return qvalidator::acceptable; else return qvalidator::intermediate; }
Comments
Post a Comment