c++ - QSpinBox with Unsigned Int for Hex Input

标签 c++ qt hex unsigned-integer qspinbox

这里写了很多关于 QSpinBox 使用 int 作为其数据类型的限制的问题。人们通常希望显示更大的数字。在我的例子中,我希望能够以十六进制显示一个无符号的 32 位整数。这意味着我希望我的范围是 [0x0, 0xFFFFFFFF]。一个正常的 QSpinBox 可以容纳的最大空间是 0x7FFFFFFF。在这里回答我自己的问题,我想出的解决方案是通过重新实现相关的显示和验证功能,简单地强制将 int 视为 unsigned int。

最佳答案

结果非常简单,而且效果很好。在这里分享以防其他人可以从中受益。它有 32 位模式和 16 位模式。

Example of HexSpinBox

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);
    }

};

关于c++ - QSpinBox with Unsigned Int for Hex Input,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26581444/

相关文章:

c++ - 是否可以在数组上使用 const_cast 来更改元素?

c++ - 程序意外结束 - QT creator

java - 将字节数组转换为十进制

c++ - 如何检查鼠标点击是否在某个区域

c++ - 在 C++ 中使用数组创建哈希表表示

c++ - deadline_timer 奇怪的行为

c++ - QCustomPlot 重新绘制 QCPLayer

c++ - Qt 接口(interface)类

c - Control+问号的十六进制代码?

regex - 用 sed 剥离十六进制字节 - 不匹配