自定义Qt窗口部件

hexspinbox.h
 1 #ifndef HEXSPINBOX_H
 2 #define HEXSPINBOX_H
 3 
 4 #include <QSpinBox>
 5 
 6 class QRegExpValidator; //正则表达式验证器 validator验证器
 7 
 8 class HexSpinBox : public QSpinBox
 9 {
10     Q_OBJECT
11 public:
12     HexSpinBox(QWidget *parent = 0); 
13 
14 protected:
15     QValidator::State validate(QString &text, int &pos) const;
16     int valueFromText(const QString &text) const;
17     QString textFromValue(int value) const;
18 
19 private:
20     QRegExpValidator *validator;
21 };
22 #endif // HEXSPINBOX_H

QValidator

The QValidator class provides validation of input text.

The class itself is abstract. Two subclasses, QIntValidator and QDoubleValidator, provide basic numeric-range checking, and QRegExpValidator provides general checking using a custom regular expression.

enum QValidator::State

This enum type defines the states in which a validated string can exist.

ConstantValueDescription
QValidator::Invalid 0 The string is clearly invalid.
QValidator::Intermediate 1 The string is a plausible intermediate value.
QValidator::Acceptable 2 The string is acceptable as a final result; i.e. it is valid.

 

QRegExpValidator

The QRegExpValidator class is used to check a string against a regular expression.

hexspinbox.cpp
 1 #include <QtGui>
 2 #include "hexspinbox.h"
 3 
 4 HexSpinBox::HexSpinBox(QWidget *parent)
 5 {
 6     setRange(0, 255);
 7     validator = new QRegExpValidator(QRegExp("[0-9A-Fa-f]{1,8}"), this);
 8 }
 9 
10 QValidator::State HexSpinBox::validate(QString &text, int &pos) const
11 {
12     return validator->validate(text, pos);
13 }
14 
15 int HexSpinBox::valueFromText(const QString &text) const
16 {
17     bool ok;
18     return text.toInt(&ok, 16);
19 }
20 
21 QString HexSpinBox::textFromValue(int value) const
22 {
23     return QString::number(value, 16).toUpper();
24 }

QValidator::State QRegExpValidator::validate ( QString & input, int & pos ) const [virtual]

Reimplemented from QValidator::validate().

Returns Acceptable if input is matched by the regular expression for this validator, Intermediate if it has matched partially (i.e. could be a valid match if additional valid characters are added), and Invalid if input is not matched.

The pos parameter is set to the length of the input parameter.

For example, if the regular expression is \w\d\d (word-character, digit, digit) then "A57" is Acceptable, "E5" isIntermediate, and "+9" is Invalid.

See also QRegExp::exactMatch().

main.cpp
 1 #include <QApplication>
 2 #include "hexspinbox.h"
 3 
 4 int main(int argc, char *argv[])
 5 {
 6     QApplication app(argc, argv);
 7     HexSpinBox spinBox;
 8     spinBox.setWindowTitle(QObject::tr("Hex Spin Box"));
 9     spinBox.show();
10     return app.exec();
11 }

 

 

posted @ 2012-12-15 21:54  永不指步  阅读(307)  评论(0编辑  收藏  举报