关于QSpinBox的子类化的详解,下面先是:HEXSPINBOX.H文件里面的内容:
#ifndef HEXSPINBOX_H
#define HEXSPINBOX_H
#include <QSpinBox>
class QRegExpValidator;
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:
QRegExpValidator *validator;
};
#endif // HEXSPINBOX_H
在protected下的:
QValidator::State validate(QString &text, int &pos) const;
这里QValidator::State是检查用户输入合法性的返回状态,其中有三种状态:Invalid:无效的,Intermediate:部分无效的,Acceptable:可以接受的,这里的pos参数用来设置text参数的长度,下面是QT html下的解释:
enum QValidator::State
This enum type defines the states in which a validated string can exist.
Constant | Value | Description |
---|---|---|
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. |
int valueFromText(const QString &text)const;
这是将字符串转换成整形数值,子类如果需要显示非数值的spinbox,就需要初始化这一个function.
QString textFromValue(int value)const;
这个虚函数用来用来显示被赋予的值,将这个值转换成QString类型并返回,如果你重新实现了这个函数,那么必须重新实现valueFromText();
下面再来看看hexspinbox.cpp文件的实现:
#include "hexspinbox.h"
#include <QtGui>
HexSpinBox::HexSpinBox(QWidget *parent) :
QSpinBox(parent)
{
setRange(0,255);
validator = new QRegExpValidator(QRegExp("[0-9A-Fa-f]{1,8}"),this);
}
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);
}
HexSpinBox::~HexSpinBox()
{
}
首先 构造函数
HexSpinBox::HexSpinBox(QWidget *parent) : QSpinBox(parent)
这里的继承就不说了,我们看setRange();这里是设置spinbox可接受数值变化的范围,原型如下:
void QSpinBox::setRange ( int minimum, int maximum )
等价于:
setMinimum(minimum);
setMaximum(maximum);
validator = new QRegExpValidator(QRegExp("[0-9A-Fa-f]{1,8}"),this);
为validator分配内存空间,QRegExpValidator用来检查输入的合法性,所以字符必须是0...9 A.....F a.....f 中的一个,可以接受1到8个字符,其原型如下:
QRegExpValidator::QRegExpValidator ( const QRegExp & rx, QObject * parent )
QString HexSpinBox::textFromValue(int value) const
{
return QString::number(value, 16).toUpper();
}
这里的number(value,16)是将value的值转换成十六进制,并通过toUpper()转换成大写。
int HexSpinBox::valueFromText(const QString &text) const
{
bool ok;
return text.toInt(&ok, 16);
}
这里就相反了,把text的值转换成整形
到这里为止QSpinBox子类化已经实现了,那么来编写下main.cpp来看看效果吧:main.cpp如下:
#include <QtGui/QApplication>
#include "hexspinbox.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
HexSpinBox *spinbox = new HexSpinBox;
spinbox->sizeHint();
spinbox->show();
return a.exec();
}
这就是子类化后的效果了......