Is there a QString
function that takes the type int as an argument and returns it as QString
?
Translation of the question “How to convert int to QString? ” @Ahmad .
Answer 1, authority 100%
Method 1
Use QString :: number ()
:
int i = 42;
QString s = QString :: number (i);
Method 2
You can use the arg
method:
QString QString :: arg (int a, int fieldWidth = 0, int base = 10, const QChar & amp; fillChar = QLatin1Char ('')) const
Method 3
And if you want to use the solution when concatenating strings, forget the +
operator. Just do it like this:
// 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);
Method 4
Another way is to use QTextStream and the & lt; & lt;
is similar to how you would use cout
in C++:
QPoint point (5,1);
QString str;
QTextStream (& amp; str) & lt; & lt; "Mouse click: (" & lt; & lt; point.x () & lt; & lt; "," & lt; & lt; point.y () & lt; & lt; ").";
// OUTPUT:
// Mouse click: (5, 1).
Because the & lt; & lt;
operator is overridden, it can be used for several types, not just int
. QString :: arg ()
is overridden, for example, arg (int a1, int a2)
, but arg (int a1, QString a2) is missing
, so using QTextStream ()
and the & lt; & lt;
operator is useful when formatting longer, mixed-type strings.
Warning : You might want to use sprintf ()
to reproduce printf ()
statements in C style, but I recommend using QTextStream
or arg ()
as they support Unicode
strings.
Method 5
Take a look at QString :: setNum ()
.
int i = 10;
double d = 10.75;
QString str;
str.setNum (i);
str.setNum (d);
setNum ()
is overridden in many ways. See the reference description for the QString
class.
Method 6
Moreover, you can use QVariant
to convert from different formats and to different formats. To convert int
to QString
we get:
QVariant (3) .toString ();
To convert type float
to String
or String
to float
:
QVariant (3.2) .toString ();
QVariant ("5.2"). ToFloat ();
Based on answers in “How to convert int to QString? “.
Answer 2, authority 7%
casting a variable to a string type
QString str = QString ("% 1"). arg (x)
Or formatted string
QString str = QString ("x1 =% 1 x2 =% 2"). arg (x1) .arg ( x2)