如何将QDoubleSpinBox设置为科学计数法?

时间:2019-01-21 18:11:33

标签: c++ qt

QDoubleSpinBox默认使用小数点显示数字

number in decimal point notation

并且我正在尝试将其格式化为科学计数法

number in scientific notation

我的解决方案是子类QDoubleSpinBox并重新定义方法validatevalueFromTexttextFromValue

class SciNotDoubleSpinbox : public QDoubleSpinBox
{
    Q_OBJECT
public:
    explicit SciNotDoubleSpinbox(QWidget *parent = 0) : QDoubleSpinBox(parent) {}

    // Change the way we read the user input
    double valueFromText(const QString & text) const
    {
        double numFromStr = text.toDouble();
        return numFromStr;
    }

    // Change the way we show the internal number
    QString textFromValue(double value) const
    {
        return QString::number(value, 'E', 6);
    }

    // Change the way we validate user input (if validate => valueFromText)
    QValidator::State validate(QString &text, int&) const
    {

        // Try to convert the string to double
        bool ok;
        text.toDouble(&ok);
        // See if it's a valid Double
        QValidator::State validationState;
        if(ok)
        {
            // If string conversion was valid, set as ascceptable
            validationState = QValidator::Acceptable;

        }
        else
        {
            // If string conversion was invalid, set as invalid
            validationState = QValidator::Invalid;
        }
        return validationState;
    }
};

它可以工作,但是validate似乎草率。它尝试使用Qt的toDouble将数字转换为两倍,并根据转换是否成功返回有效或无效状态。它甚至不使用位置。

有没有一种方法可以以一种“更干净”的方式验证科学计数法中的字符串?

0 个答案:

没有答案