[ fromfile: validation.xml id: home-made-valid ]
Example 14.9. src/validate/palindrome/palindate.h
#include <QValidator> #include <QString> class Palindate : public QValidator { Q_OBJECT public: explicit Palindate(QObject* parent = 0); QValidator::State validate(QString& input, int&) const; };
The QValidator class has one required override, validate()
, defined in Example 14.10.
It makes a lowercase copy, inpStr
, of the given string, and removes all white space and punctuation from it.
Example 14.10. src/validate/palindrome/palindate.cpp
[ . . . . ] QValidator::State Palindate::validate(QString& str, int& ) const { QString inpStr(str.toLower()); QString skipchars("-_!,;. \t"); foreach(QChar ch, skipchars) inpStr = inpStr.remove(ch); QString revStr; for(int i=inpStr.length(); i > 0; --i) revStr.append(inpStr[i-1]); if(inpStr == revStr) return Acceptable; else return Intermediate; }
Example 14.11. src/validate/palindrome/palindromeform.h
[ . . . . ] class PalindromeForm : public QWidget { Q_OBJECT public: PalindromeForm(QWidget* parent=0); QString getPalindrome(); public slots: void showResult(); void again(); private: Palindate* m_Palindate; QLineEdit* m_LineEdit; QLabel* m_Result; QString m_InputString; void setupForm(); }; [ . . . . ]
Example 14.12. src/validate/palindrome/palindromeform.cpp
[ . . . . ] PalindromeForm::PalindromeForm(QWidget* parent) : QWidget(parent), m_Palindate(new Palindate), m_LineEdit(new QLineEdit), m_Result(new QLabel) { setupForm(); } void PalindromeForm::setupForm() { setWindowTitle("Palindrome Checker"); m_LineEdit->setValidator(m_Palindate); connect(m_LineEdit, SIGNAL(returnPressed()), this, SLOT(showResult())); [ . . . . ] } void PalindromeForm::showResult() { QString str = m_LineEdit->text(); int pos(0); if(m_Palindate->validate(str,pos) == QValidator::Acceptable) { m_InputString = str; m_Result->setText("Valid Palindrome!"); } else { m_InputString = ""; m_Result->setText("Not a Palindrome!"); } } [ . . . . ]
Generated: 2012-03-02 | © 2012 Alan Ezust and Paul Ezust. |