"Preferences" menu item on Mac OS: setting QAction::PreferencesRole breaks localization



  • My application uses my own translator that loads strings from my own localization files (not .qm). No problem here. Now, consider Mac OS: some menu items, like Preferences, About and Exit, need special treatment - they should be placed in the "Application Name" category in the menu. To achieve that, I set the appropriate role for that menu item:

    ui.actionPreferences->setMenuRole(QAction::PreferencesRole);
    

    Problem: this works, but when I switch the application to another language, this item is still called "Preferences" - it remains English. Even calling ui.actionPreferences->setText("12345"); after switching the language has no effect.

    How can I fix this? The problem is two-fold:

    1. I want to supply my own translations;
    2. even if I'm going to agree on using Qt's default names for these menu items, it's not clear how I can combine that with my own Translator class. Certainly not looking forward to including the .qm files in my .app, either.


  • I think you can access this menu via Cocoa and change the titles yourself.

    You can create a special class for calling Cocoa methods like that:
    CocoaBridge.h

    #ifndef COCOABRIDGE_H
    #define COCOABRIDGE_H
    
    class CocoaBridge
    {
    
    		CocoaBridge() {}
    
    	public:
    
        static void setMainMenu();
    
    };
    
    #endif // COCOABRIDGE_H
    

    CocoaBridge.mm

    #import <Cocoa/Cocoa.h>
    
    void CocoaBridge::setMainMenu()
    {
        NSMenu* menu=[NSApp mainMenu];
        NSMenu* menuApp=[[menu itemAtIndex:0] submenu];  // Application menu
        NSLog(@"%@",[menuApp itemArray]);
    // change the titles here
    }
    

    You need to add the folowing in your .pro file

    macx{
    
        HEADERS +=		CocoaBridge.h
    
     OBJECTIVE_SOURCES +=	CocoaBridge.mm 
    
     LIBS +=		-framework AppKit
    }
    

  • Lifetime Qt Champion

    Hi,

    See the macOS specifics here for handling the application menu translation.



  • @SGaist said in "Preferences" menu item on Mac OS: setting QAction::PreferencesRole breaks localization:

    Hi,

    See the macOS specifics here for handling the application menu translation.

    Thank you, great answer as always. Don't know why I couldn't Google that, duh.
    Anyway, one thing is unclear from that guide: how can I (if at all possible) retranslate the menus at runtime? My application does support live selection of the language (application relaunch not required).


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.