Question

You know that everywhere you need a QString object as a parameter you can use just c style strings . For example showMessage function needs QString. But I passed a C-style string to this function and every thing is OK. I mean here we can think of "%1 a sample text" as a QString object! maybe!

statusBar()->showMessage("%1 a sample text");

But why can't we use this code:

statusBar()->showMessage("%1 a sample text".arg("This is "));
Was it helpful?

Solution

Because implicit-conversion to QString will be used, when passed const char[] to function and there is no implicit-conversion, without call to function, so, you are trying to call method arg on const char[], that is incorrect, construct QString by

statusBar()->showMessage(QString("%1 a sample text").arg("This is "));

and all will be fine.

OTHER TIPS

Anything in the form of "..." is of the type const char*, and thus not a QString. This is a side effect of C++ having to be compatible with C.

However, in certain situations (e.g. operator+), implicit conversion to QString is allowed, as QString has a constructor taking a parameter of the type const char*. In this case, however, you need to use explicit conversion, i.e.

statusBar()->showMessage(QString("%1 a sample text").arg("This is "));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top