8 c++ qt hex unsigned-integer qspinbox
这里有很多关于QSpinBox使用int作为其数据类型的限制的问题.通常人们想要显示更大的数字.在我的例子中,我希望能够以十六进制显示无符号的32位整数.这意味着我希望我的范围为[0x0,0xFFFFFFFF].普通QSpinBox可以达到的最大值是0x7FFFFFFF.在这里回答我自己的问题,我提出的解决方案是通过重新实现相关的显示和验证功能,简单地强制int被视为unsigned int.
小智 8
结果很简单,效果很好.在这里分享以防其他人可以从中受益.它具有32位模式和16位模式.

class HexSpinBox : public QSpinBox
{
public:
HexSpinBox(bool only16Bits, QWidget *parent = 0) : QSpinBox(parent), m_only16Bits(only16Bits)
{
setPrefix("0x");
setDisplayIntegerBase(16);
if (only16Bits)
setRange(0, 0xFFFF);
else
setRange(INT_MIN, INT_MAX);
}
unsigned int hexValue() const
{
return u(value());
}
void setHexValue(unsigned int value)
{
setValue(i(value));
}
protected:
QString textFromValue(int value) const
{
return QString::number(u(value), 16).toUpper();
}
int valueFromText(const QString &text) const
{
return i(text.toUInt(0, 16));
}
QValidator::State validate(QString &input, int &pos) const
{
QString copy(input);
if (copy.startsWith("0x"))
copy.remove(0, 2);
pos -= copy.size() - copy.trimmed().size();
copy = copy.trimmed();
if (copy.isEmpty())
return QValidator::Intermediate;
input = QString("0x") + copy.toUpper();
bool okay;
unsigned int val = copy.toUInt(&okay, 16);
if (!okay || (m_only16Bits && val > 0xFFFF))
return QValidator::Invalid;
return QValidator::Acceptable;
}
private:
bool m_only16Bits;
inline unsigned int u(int i) const
{
return *reinterpret_cast<unsigned int *>(&i);
}
inline int i(unsigned int u) const
{
return *reinterpret_cast<int *>(&u);
}
};
Run Code Online (Sandbox Code Playgroud)