QDoubleSpinBox默认使用小数点显示数字
我正在尝试将其格式化为科学记数法
我的解决方案是子类化QDoubleSpinBox并重新定义方法validate,valueFromText和textFromValue。
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;
}
};
Run Code Online (Sandbox Code Playgroud)
它有效,但validate看起来很草率。它尝试使用 Qt 将数字转换为 double toDouble,并返回有效或无效状态,具体取决于转换是否成功。它甚至不使用该位置。
有没有一种方法可以以“更干净”的方式验证科学计数法中的字符串?