使用 Qstring::toDouble 来检查数据
我正在尝试使用 QString::toDouble() 函数来验证用户输入。 文档说该函数应该像这样使用:
double QString::toDouble ( bool * ok = 0 ) const;
/*
Returns the string converted to a double value.
Returns 0.0 if the conversion fails.
If a conversion error occurs, *ok is set to false; otherwise *ok is set to true.
*/
因此,我尝试使用 *ok 来抛出错误消息(如果为 false),目的是只允许用户输入有效的整数或小数。问题是即使输入了单词,消息也始终返回有效。到目前为止,这是我的代码:
void MainWindow::checkData()
{
bool validate;
QString tempStr;
tempStr = ui->lineEditValidate->text();
double converted = tempStr.toDouble(&validate);
if (validate = false)
{
QErrorMessage validateError;
validateError.showMessage("Input is Invalid");
validateError.exec();
}
else
{
QErrorMessage worksFine;
worksFine.showMessage("valid");
worksFine.exec();
}
}
我有一种感觉,我没有正确传递 validate
参数,但文档不够可靠,我无法真正了解;也许 QString::toDouble() 函数正在将字母转换为值。
有人可以解释我哪里出了问题吗?
I'm trying to validate user input by using the QString::toDouble()
function. The documentation says the function should be used like this:
double QString::toDouble ( bool * ok = 0 ) const;
/*
Returns the string converted to a double value.
Returns 0.0 if the conversion fails.
If a conversion error occurs, *ok is set to false; otherwise *ok is set to true.
*/
So I was trying to use the *ok
to throw an error message if its false with the objective of only allowing users to enter valid integers or decimals. The problem is the message always returns valid even when words are entered. Here is my code so far:
void MainWindow::checkData()
{
bool validate;
QString tempStr;
tempStr = ui->lineEditValidate->text();
double converted = tempStr.toDouble(&validate);
if (validate = false)
{
QErrorMessage validateError;
validateError.showMessage("Input is Invalid");
validateError.exec();
}
else
{
QErrorMessage worksFine;
worksFine.showMessage("valid");
worksFine.exec();
}
}
I have a feeling that I am not passing the validate
argument properly but the documentation isn't solid enough for me to really know; maybe the QString::toDouble()
function is converting letters into values.
Could someone explain where I've gone wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这样,您就可以系统地将
validate
设置为false
,并测试该分配的结果 - 这也是false
。这是不正确的。您需要:
更常见的是省略布尔测试的比较:
或者:
您的变量最好命名为
valid
或conversionOk
或类似的名称。它不是一个操作,也不指示某些内容是否需要验证,而是指示该操作/验证的结果。With that, you're setting
validate
tofalse
systematically, and testing the result of that assignment - which isfalse
too.This is incorrect. You need:
It is even more usual to omit the comparison for boolean tests:
Or:
Your variable would be better named
valid
, orconversionOk
or something like that. It's not an action, and it doesn't indicate whether something needs validation, but the result of that action/validation.