简体   繁体   中英

How to change a QPushButton's Icon String based on QTranslator

I have an application with buttons that have icons set for the various click states, no actual QPushButton text is set or displayed; it is all contained in the icon.

These icon files include text that requires translation, and have already been generated for each language and state. I am looking for a way to use the QTranslator or QAction class to automatically select which localized version of the button to use based on the selected main language.

For example:

BTN_Media_Browse->setIcon(QIcon(QPixmap(tr(":/Images/BTN_Media_Browse_Unpressed.png"))));

I have followed the instructions on the QT Wiki: Multi Language Application but the buttons do not show up in the generated translation (.ts) files. Having a switch case for each instance of its use based on the language is not ideal.

To use different icons depending on the user's locale, you can add qresource section with lang attribute in your .qrc file.

For example:

<qresource>
    ...
    <file alias="Images/BTN_Media_Browse_Unpressed.png">Images/BTN_Media_Browse_Unpressed_en.png</file>
    ...
</qresource>
<qresource lang="de">
    ...
    <file alias="Images/BTN_Media_Browse_Unpressed.png">Images/BTN_Media_Browse_Unpressed_de.png</file>
    ...
</qresource>

Then you can use it with code like this:

BTN_Media_Browse->setIcon(QIcon(":/Images/BTN_Media_Browse_Unpressed.png"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM