What's the Q_DECLARE_TR_FUNCTIONS equivalent for namespaces?



  • Assuming I want to change this:

    class Utils
    {
      Q_DECLARE_TR_FUNCTIONS( Utils );
    
      static void foo1();
      static void foo2();
      static void foo3();
    };
    

    into what is really more reasonable:

    namespace Utils
    {
      // What's the equivalent here to declare a translation context for my utility namespace?
      // Q_DECLARE_TR_FUNCTIONS( Utils ); ???
    
      void foo1();
      void foo2();
      void foo3();
    }
    

  • Qt Champions 2016

    @Justin-Sayne
    Hello,
    Doesn't it work to simply use QObject::tr in this case? As far as I can tell Q_DECLARE_TR_FUNCTIONS only aliases the aforementioned function with a proper context ...

    PS:
    The Q_DECLARE_TR_FUNCTIONS macro is defined as:

    #define Q_DECLARE_TR_FUNCTIONS(context) \
    public: \
        static inline QString tr(const char *sourceText, const char *disambiguation = Q_NULLPTR, int n = -1) \
            { return QCoreApplication::translate(#context, sourceText, disambiguation, n); } \
        QT_DECLARE_DEPRECATED_TR_FUNCTIONS(context) \
    private:
    

    Kind regards.



  • @kshegunov
    Yes, but that's what I mean. By using contexts, this will also show up nicely ordered in QtLinguist later on, right? If I lose the ability to specify contexts for all namespaces, won't they all end up in global space later on and making translation a lot more cluttered than using a class with static utility methods and keeping the ability to wrap it inside a translation context?


  • Qt Champions 2016

    @Justin-Sayne said:

    Yes, but that's what I mean. By using contexts, this will also show up nicely ordered in QtLinguist later on, right? If I lose the ability to specify contexts for all namespaces, won't they all end up in global space later on and making translation a lot more cluttered than using a class with static utility methods and keeping the ability to wrap it inside a translation context?

    I guess so, but you could alias the function in a similar fashion. For example you could have a tr() function in the namespace that specifies the context as the namespace name. Or you could even make a macro for it (it's basically the same only the access specifiers are stripped):

    #define Q_DECLARE_NAMESPACE_TR(context) \
        inline QString tr(const char *sourceText, const char *disambiguation = Q_NULLPTR, int n = -1) \
        { return QCoreApplication::translate(#context, sourceText, disambiguation, n); }
    

    Then use it in your namespace:

    namespace MyNamespace
    {
        Q_DECLARE_NAMESPACE_TR(MyNamespace)
    
        int someFunction();
    }
    

    Kind regards.



  • @kshegunov
    Yes, that's actually a great solution. Should have thought of it myself. :D


Log in to reply
 

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