Important: Please read the Qt Code of Conduct -

QTranslator - translate defines in headers

  • Hello,
    how could I translate defines in headers?

    • tr("text") is not available in .h files
    • QT_TR_NOOP("text") and QT_TRANSLATE_NOOP("source", "text") adds text for translate to .ts file but it doesn't take translated text from .qm file
    • tr(DEFINED_TEXT_IN_HEADER) in .cpp doesn't work

    Do you know how to do that?

  • Can you post your .h file?
    is it a QObject derived class?
    did you include Q_OBJECT?

  • Moderators

    also make sure that the translator is installed before the tr() methods are called.
    If it is (re-)installed later, you need to make sure you reassign all the strings using the tr() method again.

  • I have class texts, there are defines I need to translate:

    // texts.h ------------------------------------------------------------------------------------------
    #ifndef TEXTS_H
    #define TEXTS_H

    #include <QObject>

    class QLabel;
    class texts : public QObject

    #define MONDAY tr("Monday")
    #define TUESDAY tr("Tuesday")
    #define WEDNESDAY tr("Wednesday")

    explicit texts(QObject *parent = 0);
    void setText(QLabel *label);
    #endif // TEXTS_H

    // texts.cpp ------------------------------------------------------------------------------------------
    #include "texts.h"
    #include <QDebug>
    #include <QLabel>

    texts::texts(QObject *parent) : QObject(parent){}
    void texts::setText(QLabel *label)

    // mainwindow ------------------------------------------------------------------------------------------
    void MainWindow::on_pushButtoncz_clicked()
    m_pTexts->setText(ui->label_pondeli); -------> works well
    ui->label_utery->setText(MONDAY); -------> doesn´t work

    It looks like problem is that translations in .qm / .ts files are classified by class names and works only in specific classes, not works at all.

  • @pVit

    In your example the macro gets expanded in the context of MainWindow so you're calling MainWindow::tr(...) instead of texts::tr(...). This requires a separate translation.
    But the method is static so it should work when adjusting the macros as followed:

    #define MONDAY texts::tr("Monday")
    #define TUESDAY texts::tr("Tuesday")
    #define WEDNESDAY texts::tr("Wednesday")

  • @micland
    Thanks a lot! It's working now.

  • Just a note, if those are just days of the week, you can use QDate(2016,10,10).toString(QStringLiteral("dddd")). this will be the day of the week (Monday in this case as 2016-10-10 is a monday) automatically translated to the target locale, no need for manual translations.

  • @VRonin
    Thanks for info but these words were only examples, I have many more defines :)

Log in to reply