Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format a QString?

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?

like image 737
hubert poduszczak Avatar asked Jan 24 '11 16:01

hubert poduszczak


People also ask

How do you create a QString?

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.

How do you split a QString?

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.

How do you convert QString to string?

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.

How do I print a QString?

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));


2 Answers

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.

like image 74
Dat Chu Avatar answered Sep 16 '22 14:09

Dat Chu


You can use the sprintf method, however the arg method is preferred as it supports unicode.

QString str; str.sprintf("%s %d", "string", 213); 
like image 45
trojanfoe Avatar answered Sep 17 '22 14:09

trojanfoe