I want my app to be multilangual. That's why I use Object::tr
for every string in my app. Its easy, when I have this:
QObject::tr("message");
but having QString for QObject::tr
is quite long:
QString msg = "";
msg += "some kind of message";
QMessageBox msgBox;
msgBox.setText(QObject::tr(msg.toStdString().c_str()));
msgBox.setIcon(QMessageBox::Warning);
msgBox.exec();
can it be done easier?
tr() function is used for (optional) translation of given string to another languages. From this answer available on Qt forum: If you want your application to have multiple language support, wrap every user-visible string in your code inside a tr() function.
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.
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.
Since QString uses the Unicode encoding internally, every language in the world can be processed transparently using familiar text processing operations. Also, since all Qt functions that present text to the user take a QString as a parameter, there is no char * to QString conversion overhead.
When tr () is called, it looks up the translatable string using a QTranslator object. For translation to work, one or more of these must have been installed on the application object in the way described in Enabling Translation.
Note: Iterators over a QString, and references to individual characters within one, cannot be relied on to remain valid when any non- const method of the QString is called. Accessing such an iterator or reference after the call to a non- const method leads to undefined behavior.
A QString can embed '\0' characters ( QChar::Null ). The size () function always returns the size of the whole string, including embedded '\0' characters. After a call to the resize () function, newly allocated characters have undefined values. To set all the characters in the string to a particular value, use the fill () function.
You can just pass QString
through qPrintable
to the QObject::tr
.
QString msg = "";
msg += "some kind of message";
QMessageBox msgBox;
msgBox.setText(QObject::tr(qPrintable(msg)));
msgBox.setIcon(QMessageBox::Warning);
msgBox.exec();
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