Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 674
Alexandre Neto Avatar asked Aug 21 '13 15:08

Alexandre Neto


2 Answers

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, you can simply type {} without the 0.

like image 99
Frodon Avatar answered Oct 08 '22 16:10

Frodon


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)
like image 23
Alexandre Neto Avatar answered Oct 08 '22 15:10

Alexandre Neto