Question

When it comes to internationalization - using python2 and PyQt4 - the "proposed way" to format a translated string is using the QString.arg() method:

from PyQt4.QtGui import QDialog
#somewhere in a QDialog:
    self.tr("string %1 %2").arg(arg1).arg(arg2)

But QString() doesn't exist in python3-PyQt4.

So my question is, what is the best way to format any translated strings in python3? Should I use the standard python method str.format() or maybe there is something more suitable?

Was it helpful?

Solution

The QString::arg method is really there as a workaround for C++'s limited string formatting support, to make sure you don't use sprintf with all the problems that entails (not handling placeholders that are in different orders in different languages, buffer overruns, etc.). Because Python doesn't have any such problems, there's no good reason to use it.

In fact, there's very little reason to ever use QString explicitly. In PyQt4, it wasn't phased out completely, but by PyQt5, it was. (Technically, PyQt4 supports "string API v2" in both Python 2.x and 3.x, but only enables it by default in 3.x; PyQt4 enables v2 by default in both, and hides the ability to switch back to v1.) See Python Strings, Qt Strings and Unicode in the documentation for some added info.


There is one uncommon, but major if it affects you, exception: If you're writing an app that's partly in Qt/C++ and partly in PyQt, you're going to have problems sharing I18N data when some of them are in "string %1 %2" format and others are in "string {1} {2}" format. (The first time you ship one of your file out to an outsourced translation company, they're going to get it wrong, guaranteed.)

OTHER TIPS

Yes, just use standard python string formatting.

QString is gone because it's pretty much interchangable with python's unicode strings (which are str in python3 and unicode in python2), so PyQt takes care of converting one into the other as needed.

QString being disabled isn't limited to python3, it's just the default there. You can get the same on python2 by doing this befor importing anything from PyQt4:

import sip
sip.setapi('QString', 2)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top