14.2. Validators

[ fromfile: validation.xml id: validator ]

Validators are objects that can be attached to input widgets (such as QLineEdit, QSpinBox, and QComboBox), to provide a general framework for checking user input. Qt has an abstract class named QValidator that establishes the interface for all built-in and custom validators.

Two of QValidator's concrete subclasses can be used for numeric range checking: QIntValidator and QDoubleValidator. There is also a concrete subclass that can be used for validating a string with a specified regular expression. We discuss regular expressions in the next section.

QValidator::validate() is a pure virtual method that returns one of the following enumerated values:

Other member functions enable the setting of the values that validate() uses (e.g., range limits).

Generally, a working validator will not permit the user to enter data that causes it to return the value Invalid.

Example 14.3 is a short Work-Study Salary Calculator application that uses the two numerical validators. It takes an int and a double from the user and displays their product. Total Pay is computed and displayed when the user presses return.

Example 14.3. src/validate/numvalidate/inputform.h

[ . . . . ]
class InputForm : public QWidget {
    Q_OBJECT
 public:
    InputForm(int ibot, int itop, double dbot, double dtop);
 public slots:
    void computeResult();
 private:
    void setupForm();
    int m_BotI, m_TopI;
    double m_BotD, m_TopD;
    QLineEdit* m_IntEntry;
    QLineEdit* m_DoubleEntry;
    QLabel* m_Result;
};
[ . . . . ]

In Example 14.4, validators are initialized with range values in the constructor and are assigned to their respective input widgets in the setupForm() function.

Example 14.4. src/validate/numvalidate/inputform.cpp

[ . . . . ]
InputForm::InputForm(int ibot, int itop, double dbot, double dtop):
    m_BotI(ibot), m_TopI(itop), m_BotD(dbot), m_TopD(dtop),
    m_IntEntry(new QLineEdit("0")),
    m_DoubleEntry(new QLineEdit("0")),
    m_Result(new QLabel("0")) { 
    setupForm();
    move(500, 500); 1
}

void InputForm::setupForm() {
    [ . . . . ]
    QIntValidator* iValid(new QIntValidator(m_BotI, m_TopI, this));
    QDoubleValidator* 
             dValid(new QDoubleValidator(m_BotD, m_TopD, 2, this));
    m_IntEntry->setValidator(iValid);
    m_DoubleEntry->setValidator(dValid);
    connect(m_IntEntry, SIGNAL(returnPressed()), 
            this, SLOT(computeResult()));
    connect(m_DoubleEntry, SIGNAL(returnPressed()),
            this, SLOT(computeResult()));
}
[ . . . . ]

1

Start in mid screen (approx).


The running program looks like Figure 14.2.

Figure 14.2.  Work Study Calculator

Work Study Calculator