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);
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 strings.
Use
QString::number()
:And if you want to put it into string within some text context, forget about
+
operator. Simply do:Moreover to convert whatever you want, you can use
QVariant
. For anint
to aQString
you get:A
float
to astring
or astring
to afloat
:Yet another option is to use QTextStream and the
<<
operator in much the same way as you would usecout
in C++:Because operator
<<()
has been overloaded, you can use it for multiple types, not justint
.QString::arg()
is overloaded, for examplearg(int a1, int a2)
, but there is noarg(int a1, QString a2)
, so usingQTextStream()
and operator<<
is convenient when formatting longer strings with mixed types.Caution: You might be tempted to use the
sprintf()
facility to mimic C styleprintf()
statements, but it is recommended to useQTextStream
orarg()
because they support Unicodestring
s.I always use
QString::setNum()
.setNum()
is overloaded in many ways. SeeQString
class reference.In it's simplest form, use the answer of Georg Fritzsche
For a bit advanced, you can use this,
Get the documentation and an example here..
If you need locale-aware number formatting, use QLocale::toString instead.
Just for completeness, you can use the standard library and do
QString qstr = QString::fromStdString(std::to_string(42));