这个程序主要为了,练习自定义 Qt 窗体部件,HexSpinBox 实现了一个 16
进制的 SpinBox,所以只要重载 SpinBox 就可以了...详见代码
==================================================================
hexspinbox.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| #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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| #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
1 2 3 4 5 6 7 8 9 10
| #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