这个程序主要为了,练习自定义 Qt 窗体部件,HexSpinBox 实现了一个 16 进制的 SpinBox,所以只要重载 SpinBox 就可以了…详见代码
==================================================================
hexspinbox.h
| #ifndef HEXSPINBOX_H#define HEXSPINBOX_H
 #include <QtGui/QWidget>
 #include <QSpinBox>
 namespace Ui
 {
 class HexSpinBoxClass;
 }
 class HexSpinBox : public QSpinBox
 {
 Q_OBJECT
 public:
 HexSpinBox(QWidget *parent = 0);
 ~HexSpinBox();
 protected:
 QValidator::State validate(QString &text,int &pos) const;
 int valueFromText(const QString &text) const;
 QString textFromValue(int value) const;
 private:
 Ui::HexSpinBoxClass *ui;
 QRegExpValidator *validator;
 };
 #endif
 
 | 
hexspinbox.cpp
| #include "hexspinbox.h"#include "ui_hexspinbox.h"
 HexSpinBox::HexSpinBox(QWidget *parent)
 :QSpinBox(parent)
 {
 ui->setupUi(this);
 setRange(0,255);
 validator=new QRegExpValidator(QRegExp("[0-9A-Fa-f]{1,8}"),this);
 }
 HexSpinBox::~HexSpinBox()
 {
 delete ui;
 }
 
 QValidator::State HexSpinBox::validate(QString &text,int &pos) const
 {
 return validator->validate(text,pos);
 }
 
 QString HexSpinBox::textFromValue(int value) const
 {
 return QString::number(value,16).toUpper();
 }
 
 int HexSpinBox::valueFromText(const QString &text) const
 {
 bool ok;
 return text.toInt(&ok,16);
 }
 
 | 
main.cpp
| #include <QtGui/QApplication>#include "hexspinbox.h"
 int main(int argc, char *argv[])
 {
 QApplication app(argc, argv);
 HexSpinBox *hexSpinBox=new HexSpinBox;
 hexSpinBox->sizeHint();
 hexSpinBox->show();
 return app.exec();
 }
 
 | 

PS:庆祝空间人气突破 25000