Important: Please read the Qt Code of Conduct -

Qt tr() not working if i am using in static member

  • #1 Please let me know why it is not working i am new in Qt. here is the code

    #include <QApplication>
    #include <QPushButton>
    #include <QTranslator>
    class Transl
    static const QString str;
    const QString Transl::str = QObject::tr("Hello world");
    // const char* const gstr = "Hello World";

    int main(int argc, char *argv[])
    QApplication app(argc, argv);
    QTranslator translator;

    QPushButton *button =    new QPushButton();
    // button->setText(tr(gstr));   // This is also throw error "error: ‘tr’ was not declared in this scope"
    return app.exec&#40;&#41;;


    My trans_la.ts file contains this which i generate by lupdate.

    @<TS version="2.0">
    <location filename="main.cpp" line="10"/>
    <source>Hello world</source>
    <translation>Orbis, te saluto!</translation>
    </TS> @

    Then I do lrelease which generate trans_la.qm. But when i run my executable instead of showing the translated string it shows "Hello world". Please suggest me why it is not working.

    #2 Also if you see i have commented two lines(11th and 22nd) where I am trying to use with constant char* global variable where it thows error tr() was not declared in the scope.

  • Qt tr does not work on static constant members. use QT_TR_NOOP instead tr.

    @const QString Transl::str = QT_TR_NOOP("Hello world");@

  • hi @dasun i tried QT_TR_NOOP("Hello world") in that case lupdate is not working it ask tr is not working without any context. Please help :). Also can you figure out about the error of #2 why tr() is giving me error ?

  • Main function is not an QObject. tr defined in QObject.

    You can use @QObject::tr("Hello World");@

  • Lifetime Qt Champion

    Hi and welcome to devnet,

    IIRC, for static text like that it's QT_TRANSLATE_NOOP that should be used

  • Hi @SGalst what actually QT_TRANSLATE_NOOP will do ? will it work on translation ?

  • Lifetime Qt Champion

    A little search in the documentation would have returned the "explanation":

  • hey thanks for the valuable info. but i still did not find the solution of #2 why it is giving me error. well i'll try to look more in documentation. Thanks

  • Lifetime Qt Champion

    It simple: tr is a method of QObject and main is a function not a QObject

Log in to reply