I'd like to format a string for Qt label, I'm programming in C++ on Qt.
In ObjC I would write something like:
NSString *format=[NSString stringWithFormat: ... ];
How to do something like that in Qt?
One way to initialize a QString is simply to pass a const char * to its constructor. For example, the following code creates a QString of size 5 containing the data "Hello": QString str = "Hello"; QString converts the const char * data into Unicode using the fromAscii() function.
To break up a string into a string list, we used the QString::split() function. The argument to split can be a single character, a string, or a QRegExp. To concatenate all the strings in a string list into a single string (with an optional separator), we used the join() function.
You can use: QString qs; // do things std::cout << qs. toStdString() << std::endl; It internally uses QString::toUtf8() function to create std::string, so it's Unicode safe as well.
According to Qt Core 5.6 documentation you should use qUtf8Printable() from <QtGlobal> header to print QString with qDebug . You should do as follows: QString s = "some text"; qDebug("%s", qUtf8Printable(s));
You can use QString.arg like this
QString my_formatted_string = QString("%1/%2-%3.txt").arg("~", "Tom", "Jane"); // You get "~/Tom-Jane.txt"
This method is preferred over sprintf because:
Changing the position of the string without having to change the ordering of substitution, e.g.
// To get "~/Jane-Tom.txt" QString my_formatted_string = QString("%1/%3-%2.txt").arg("~", "Tom", "Jane");
Or, changing the type of the arguments doesn't require changing the format string, e.g.
// To get "~/Tom-1.txt" QString my_formatted_string = QString("%1/%2-%3.txt").arg("~", "Tom", QString::number(1));
As you can see, the change is minimal. Of course, you generally do not need to care about the type that is passed into QString::arg() since most types are correctly overloaded.
One drawback though: QString::arg() doesn't handle std::string. You will need to call: QString::fromStdString() on your std::string to make it into a QString before passing it to QString::arg(). Try to separate the classes that use QString from the classes that use std::string. Or if you can, switch to QString altogether.
UPDATE: Examples are updated thanks to Frank Osterfeld.
UPDATE: Examples are updated thanks to alexisdm.
You can use the sprintf
method, however the arg
method is preferred as it supports unicode.
QString str; str.sprintf("%s %d", "string", 213);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With