Alexandre Neto
Alexandre Neto

Reputation: 207

Whats the correct way to translate a "dynamic" string in PyQt

To allow the internationalization of a Python plugin for QGIS, I'm using QCoreApplication.translate() like this:

message = QCoreApplication.translate('Multipart split',"No multipart features selected.")

How can I prepare a dynamic string, like the following,

message = "Splited " + str(n_of_splitted_features) + " multipart feature(s)" 

to translate, without the need to break each of sub-strings, like this

message = QCoreApplication.translate('Multipart split','Splited ') + str(n_of_splitted_features) + QCoreApplication.translate('Multipart split', 'multipart feature(s)')

which does not appear to be the best option.

I have found that in C++ using the tr() with .arg(), one can do this:

statusBar()->showMessage(tr("Host %1 found").arg(hostName))

But I was unable to replicate using Python.

Upvotes: 7

Views: 2713

Answers (2)

Frodon
Frodon

Reputation: 3775

Try the format command on the result of the tr method :

statusBar().showMessage(tr("Host {0} found").format(hostName))

The translation in the ts file should also contain the {0} string.

Edit: with Python 2.7 (and Python 3 obviously), you can simply type {} without the 0 if you appear to have a single argument. As Cecil mentionned, keep the numbers with the {} to deal with internationalisation.

Upvotes: 5

Alexandre Neto
Alexandre Neto

Reputation: 207

I found the solution myself, maybe it's useful for someone else.

message = QCoreApplication.translate('Multipart split', "Splited %d multipart feature(s)") %(n_of_splitted_features)

Upvotes: 1

Related Questions