Validators

Validators are nonvisual objects that are 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.

There are two concrete subclasses that 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 will discuss regular expressions in the next section.

QValidator::validate() is a pure virtual method that returns an enumerated value, as follows:

Other member functions enable the setting of the conditions that validate() uses.

In Example 13.1 we have a short app that uses the two numerical validators. It takes an int and a double from the user to display the product. Each input is given a range check when the user presses return.

Example 13.1. src/validate/inputform.h

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

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

Example 13.2. src/validate/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_IValid(new QIntValidator(ibot, itop, this)), m_DValid(new QDoubleValidator(dbot, dtop, 2, this)), [ . . . . ] void InputForm::setupForm() { [ . . . . ] m_IntEntry->setValidator(m_IValid); m_DoubleEntry->setValidator(m_DValid); connect(m_IntEntry, SIGNAL(returnPressed()), this, SLOT(computeResult())); connect(m_DoubleEntry, SIGNAL(returnPressed()), this, SLOT(computeResult())); } [ . . . . ]

The running program looks like the screenshot that follows.

If you run it, try to enter a non-int textfield, or a non-float in the second. You should notice that it does not recognize invalid characters as input.

Категории