SPlatten SPlatten - 1 year ago 225
C++ Question

Qt QString toInt() fails

I have a 'QString' containing "-3.5", however if I try to convert this to an integer using the 'toInt' method it returns 0. Why?

QString strTest = "-3.5";
int intTest = strTest.toInt();

qDebug() << intTest;

intTest will be 0 ?

Answer Source

As opposed to std::stoi and streams from the standard library, Qt strings require the whole string to be a valid integer to perform the conversion. You could use toDouble instead as a workaround.

You should also use the optional ok parameter to check for errors:

QString strTest = "-3.5";
book ok;
int intTest = strTest.toInt(&ok);
if(ok) {
    qDebug() << intTest;
} else {
    qDebug() << "failed to read the string";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download