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 QString to a std::string:

    std::string myString = qtString.toStdString();
  •  

  • Convert a std::string to a QString:

    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 QString to an integer:

    QString myString = "42";
    int theAnswer = myString.toInt();
  •  

  • Convert a QString to 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 + sign

    double changeInPrice = 1.25;
    QString qtString = QString().asprintf("%+0.2f", changeInPrice); // +1.25
  •  

  • Convert a number to a QString, and format it with comma separators

    int volume = 37800900;
    QString qtString = QLocale(QLocale::English).toString(volume); // 37,800,900