14.5.  Subclassing QValidator

[ 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;
};


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);       1
   QString revStr;                      2
   for(int i=inpStr.length(); i > 0; --i) 
      revStr.append(inpStr[i-1]);
   if(inpStr == revStr) 
      return Acceptable;
   else
      return Intermediate;
}

1

You could do this faster with a regex.

2

Surprising there is no reverse() function.


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!");
   }
}
[ . . . . ]

Figure 14.5.  Palindrome Checker

Palindrome Checker