本文介绍了带有用于十六进制输入的无符号整数的QSpinBox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里有关于QSpinBox的限制使用int作为其数据类型的各种问题。通常人们想要显示更大的数字。在我的情况下,我想能够显示一个无符号32位整数的十六进制。这意味着我想要我的范围是[0x0,0xFFFFFFFF]。一个正常的QSpinBox可以去的最大是0x7FFFFFFF。在这里回答我自己的问题,我想出的解决方案是简单地强制int被处理像一个unsigned int,通过重新实现相关的显示和验证函数。

There are a variety of questions written here about QSpinBox's limitation of using an int as its datatype. Often people want to display larger numbers. In my case, I want to be able to show an unsigned 32bit integer in hexadecimal. This means I'd like my range to be [0x0, 0xFFFFFFFF]. The largest a normal QSpinBox can go is 0x7FFFFFFF. Answering my own question here, the solution I came up with is to simply force the int to be treated like an unsigned int, by reimplementing the relevant display and validation functions.

推荐答案

结果很简单,运行良好。在这里分享,以防其他任何人都能从中受益。它有一个32位模式和一个16位模式。

The result is pretty simple, and it works well. Sharing here in case anyone else can benefit from this. It has a 32bit mode and a 16bit mode.

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

};

这篇关于带有用于十六进制输入的无符号整数的QSpinBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-16 17:28