加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 带有无符号Int的QSpinBox,用于十六进制输入

发布时间:2020-12-16 03:32:34 所属栏目:百科 来源:网络整理
导读:这里有很多关于QSpinBox使用int作为其数据类型的限制的问题.通常人们想要显示更大的数字.在我的例子中,我希望能够以十六进制显示无符号的32位整数.这意味着我希望我的范围为[0x0,0xFFFFFFFF].普通QSpinBox可以达到的最大值是0x7FFFFFFF.在这里回答我自己的问
这里有很多关于QSpinBox使用int作为其数据类型的限制的问题.通常人们想要显示更大的数字.在我的例子中,我希望能够以十六进制显示无符号的32位整数.这意味着我希望我的范围为[0x0,0xFFFFFFFF].普通QSpinBox可以达到的最大值是0x7FFFFFFF.在这里回答我自己的问题,我提出的解决方案是通过重新实现相关的显示和验证功能,简单地强制int被视为unsigned int.

解决方法

结果很简单,效果很好.在这里分享以防其他人可以从中受益.它具有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);
    }

};

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读