PDA

View Full Version : Good way to use QString.arg() to just format an int?



tuli
11th November 2018, 00:44
Hi,

I want to convert some integer to hex-string and pad it with 0.

So far I would do, e.g.


QString().sprintf("%.8X ", quint32(111));

Now I am thinking about dropping use of format strings in new code, and Qt tells me to avoid Qstring::sprintf too and use arg() instead. So I could do



QString("%1").arg(111, 8, 16, '0')


Question: Is there any way to use arg() to avoid having to parse the "%1" format string and just get the string value of arg() call?

Is there any other Qt-way to achieve this with more performance?

Thanks.

d_stranz
11th November 2018, 17:56
Question: Is there any way to use arg() to avoid having to parse the "%1" format string and just get the string value of arg() call?

Usually you would be using arg() with a variable argument, not a fixed value like 111. If you are formatting a hex string with a fixed value, then just create the string literal and be done with it. The "%1" syntax is just a way to put placeholders in a QString when using arg() with variable arguments to say "Put the result of the first arg() expression into this position". Usually, it is more common for the placeholders to be part of a longer formatted string, not just the placeholder all alone:


int a = 111;
QString( "The conversion of %1 to hex is %2" ).arg( a ).arg( a, 8, 16, '0' );

tuli
11th November 2018, 19:42
I just need the sprintf'ing effect of arg().


Essentially I want to string-ify a variable (or constant, doesnt matter) to a string of format "as hex, and padded with zeros up to 8 chars".


Both sprintf and arg() require parsing a format string, that (as you said) i am not really using. So I am looking for the best way to do this via Qt, but it looks like there is no better way.

d_stranz
11th November 2018, 23:30
I suppose QString::number() with a base = 16 would do it, but it won't give you any format or padding options. But basically, if you want to use QString::arg(), you also must use a placeholder argument in the QString literal that forms the left-hand-side of the expression. Not sure why you object to this so much - it's the way the function is defined. Not a whole lot different from Python's "{0} {1}" formatting convention (although supposedly Python 3.1 lets you get away with "{} {}", but the string literal with braces is still required to format the output).