How to convert int to QString?
Solution 1:
Use QString::number()
:
int i = 42;
QString s = QString::number(i);
Solution 2:
And if you want to put it into string within some text context, forget about +
operator.
Simply do:
// Qt 5 + C++11
auto i = 13;
auto printable = QStringLiteral("My magic number is %1. That's all!").arg(i);
// Qt 5
int i = 13;
QString printable = QStringLiteral("My magic number is %1. That's all!").arg(i);
// Qt 4
int i = 13;
QString printable = QString::fromLatin1("My magic number is %1. That's all!").arg(i);
Solution 3:
Moreover to convert whatever you want, you can use QVariant
.
For an int
to a QString
you get:
QVariant(3).toString();
A float
to a string
or a string
to a float
:
QVariant(3.2).toString();
QVariant("5.2").toFloat();
Solution 4:
Yet another option is to use QTextStream and the <<
operator in much the same way as you would use cout
in C++:
QPoint point(5,1);
QString str;
QTextStream(&str) << "Mouse click: (" << point.x() << ", " << point.y() << ").";
// OUTPUT:
// Mouse click: (5, 1).
Because operator <<()
has been overloaded, you can use it for multiple types, not just int
. QString::arg()
is overloaded, for example arg(int a1, int a2)
, but there is no arg(int a1, QString a2)
, so using QTextStream()
and operator <<
is convenient when formatting longer strings with mixed types.
Caution: You might be tempted to use the sprintf()
facility to mimic C style printf()
statements, but it is recommended to use QTextStream
or arg()
because they support Unicode string
s.
Solution 5:
I always use QString::setNum()
.
int i = 10;
double d = 10.75;
QString str;
str.setNum(i);
str.setNum(d);
setNum()
is overloaded in many ways. See QString
class reference.