📜  c++ int to qstring - C++ (1)

📅  最后修改于: 2023-12-03 15:13:54.387000             🧑  作者: Mango

C++ Int to QString

In C++, an int variable can be converted to a QString using the QString::number() function. This function returns a QString that represents the given integer value.

#include <QString>

int main()
{
    int num = 42;
    QString str = QString::number(num); // "42"
    return 0;
}

The QString::number() function also accepts a second argument that specifies the base of the number to convert. By default, it converts the number to base 10, but it can also convert to base 2, base 8, base 16, or any other base between 2 and 36.

#include <QString>

int main()
{
    int num = 42;
    QString str2 = QString::number(num, 2); // "101010"
    QString str8 = QString::number(num, 8); // "52"
    QString str16 = QString::number(num, 16); // "2a"
    return 0;
}

It is also possible to convert a std::string to a QString using the QString::fromStdString() function.

#include <QString>

int main()
{
    std::string str = "Hello World!";
    QString qstr = QString::fromStdString(str);
    return 0;
}

Note that the QString::fromStdString() function copies the contents of the std::string object into a new QString object. If you need to avoid this copy, you can use a QString constructor that takes a C-style string.

#include <QString>

int main()
{
    std::string str = "Hello World!";
    QString qstr = QString::fromUtf8(str.c_str());
    return 0;
}

In this example, the std::string object is converted to a C-style string using the c_str() member function, and then the QString::fromUtf8() function creates a new QString object that points to the same memory location as the C-style string. This avoids any unnecessary copies of the string data.

Overall, C++ provides several ways to convert an int variable to a QString object, depending on your requirements for the resulting string representation and the source of the integer value.