1. hexspinbox.cpp
1 /* 2 * The spin box supports integer values but can be extended to use different strings 3 * with validate(), textFromValue() and valueFromText(). 4 */ 5 #include "hexspinbox.h" 6 7 #include <QRegExpValidator> 8 9 HexSpinBox::HexSpinBox(QWidget *parent) 10 : QSpinBox(parent) 11 { 12 setRange(0, 255); /*设置默认范围是从0到255*/ 13 validator = new QRegExpValidator(QRegExp("[0-9A-Fa-f]{1,8}"), this); 14 } 15 16 QValidator::State HexSpinBox::validate(QString &text, int &pos) const 17 { 18 return validator->validate(text, pos); 19 } 20 21 QString HexSpinBox::textFromValue(int value) const 22 { 23 return QString::number(value, 16).toUpper(); 24 } 25 26 int HexSpinBox::valueFromText(const QString &text) const 27 { 28 bool ok; 29 return text.toInt(&ok, 16); 30 }
2. hexspinbox.h
1 #ifndef HEXSPINBOX_H 2 #define HEXSPINBOX_H 3 4 #include <QSpinBox> 5 6 class QRegExpValidator; 7 8 class HexSpinBox : public QSpinBox 9 { 10 Q_OBJECT 11 12 public: 13 HexSpinBox(QWidget *parent = 0); 14 15 protected: 16 QValidator::State validate(QString &text, int &pos) const; 17 QString textFromValue(int value) const; 18 int valueFromText(const QString &text) const; 19 20 private: 21 QRegExpValidator *validator; 22 }; 23 24 25 #endif /*HEXSPINBOX_H*/
3. main.cpp
1 #include <QApplication> 2 3 #include "hexspinbox.h" 4 5 int main(int argc, char *argv[]) 6 { 7 QApplication app(argc, argv); 8 9 HexSpinBox *hexSpinBox = new HexSpinBox; 10 hexSpinBox->show(); 11 12 return app.exec(); 13 }
4. 效果