Qt: Converting Text and Numbers to and from QString
×
NOTE: For examples of converting standard C++ strings to numbers,
follow this link.
This page provides several examples of how to convert among
QString objects, standard C++ strings, and numbers.
Remember to include the necessary
Qt class headers for QString and QLocale!
-
Convert a
QStringto astd::string:std::string myString = qtString.toStdString();
-
Convert a
std::stringto aQString:std::string myString = “Do you like football?”;
QString qtString = QString::fromStdString(myString); -
Convert a number to a
QString:int theAnswer = 42;
QString qtString = QString::number(theAnswer); -
Convert a
QStringto an integer:QString myString = "42";
int theAnswer = myString.toInt(); -
Convert a
QStringto a double:QString gpaString = "3.75";
double gpa = gpaString.toDouble(); -
Convert a number to a
QString, and format it to two decimal places:double price = 89.0278;
QString qtString = QString().asprintf("%0.2f", price); // 89.03 -
Convert a number to a
QString, and format it to two decimal places with a leading + signdouble changeInPrice = 1.25;
QString qtString = QString().asprintf("%+0.2f", changeInPrice); // +1.25 -
Convert a number to a
QString, and format it with comma separatorsint volume = 37800900;
QString qtString = QLocale(QLocale::English).toString(volume); // 37,800,900