Get Value of DoubleSpinBox into a double or float
-
Hello again,
I have a simple calculation:double a = QVariant(ui->input_a->text()).toDouble(); int b = QVariant(ui->input_b->text()).toInt(); double d = 0; d = b / (a * a); ui->text_result->setText(QVariant(d).toString());
When I compile it, no error is shown, but when I edit the Values with the DoubleSpinBoxes, then the Value
a
doesn't change. (i.e. It's0
.)Code for checking Values:
ui->text_result->setText("Error! " + QVariant(a).toString() + "|" + QVariant(b).toString());
Before, I used Floats, but because I read, it was better, when I use double I changed the format. (Because of precision, ...)
The Debugger isn't saying anything about this. -
QVariant
doesn't not do the conversion for you. It's just a means to store any type, but if you store aQString
in it, thenQVariant::toDouble()
will not convert it to a double for you.Instead, use
QString::toDouble()
:bool ok = false; double a = ui->input_a->text().toDouble(&ok); if (!ok) { qDebug("Conversion failed!"); }
Reasons for why
QString::toDouble()
might fail are simple format issues. You can prevent those by using aQValidator
. Alternatively, if yourinput_a
contains composite strings you can use a regex to extract your double.@tomaschku said in Get Value of DoubleSpinBox into a double or float:
Before, I used Floats, but because I read, it was better, when I use double I changed the format. (Because of precision, ...)
The question is whether you need the precision.
-
Err... I just read your title... You seem to use
QDoubleSpinBox
? If so, why not just usingQDoubleSpinBox::value()
which returns adouble
? There is noQDoubleSpinBox::text()
so I'm not sure if you're mixing things up (or if you're usingQDoubleSpinBox::textFromValue()
but in any case, if you're usingQDoubleSpinBox
then usingQDoubleSpinBox::value()
is the right way to go. If you use something else, such asQLineEdit
, then the stuff I mentioned in my first post is the way to go. -
@Joel-Bodenmann Thank you, for your answer. I'm very new with the UI-Version of C++ and I don't know so much about it... :)
-
You're welcome - we're here to help :)
Please mark this topic as solved if your questions have been answered.
-
@Joel-Bodenmann said in Get Value of DoubleSpinBox into a double or float:
QVariant doesn't not do the conversion for you.
Just as a note here,
QVariant
actually does conversions. Whether or not a conversion is possible can be judged by the return value of QVariant::canConvert. -
@tomaschku said in Get Value of DoubleSpinBox into a double or float:
Code for checking Values:
ui->text_result->setText("Error! " + QVariant(a).toString() + "|" + QVariant(b).toString());when I edit the Values with the DoubleSpinBoxes, then the Value a doesn't change. (i.e. It's 0.)
I think the problem is even worse than what is mentioned above.
double a = ui->input_a->value();
does not imply that wheninput_a
changes it automatically updatesa