38

Qt's translation function tr does not work in the main function but works fine in a QWidget member function. Why is that?

int main(int argc, char *argv[])
{

    QApplication a(argc, argv);
    QDialog dialog; 
    QString temp = tr("dadasda");//error:tr was not declared in this scope
    dialog.show();
    return a.exec();
}
Josh Darnell
  • 11,304
  • 9
  • 38
  • 66
Passionate programmer
  • 5,748
  • 10
  • 39
  • 43
  • 1
    Just a tiny bit more info? Please? Like, some code or something? – balpha Jan 07 '10 at 11:52
  • 3
    sorry seems tr function is static function inside QObject and most of the time QObject is inherited in other widget they directly use tr, but in my case it has to be QObject::tr works – Passionate programmer Jan 07 '10 at 11:57
  • someone can close it as no more relevant – Passionate programmer Jan 07 '10 at 11:59
  • 1
    Then it would be nice if you wrote that into an answer, possibly with some example code, and put a little more effort into the question. If you then accept your own answer, that will even give you a self-lerner badge. People then having this (actually good) question will find this information in the future. – balpha Jan 07 '10 at 11:59

1 Answers1

82

The translation function tr is a static method of QObject. Since QWidget is a subclass of QObject, tr is available in methods of QWidget, but in main() you have to use QObject::tr in order to use the function, as shown below.

#include <QObject>
int main(int argc, char *argv[])
{   
    QApplication a(argc, argv);
    QDialog dialog; 
    QString temp = QObject::tr("dadasda");//works fine
    dialog.show();
    return a.exec();
}
balpha
  • 50,022
  • 18
  • 110
  • 131
Passionate programmer
  • 5,748
  • 10
  • 39
  • 43
  • tr works only for Q_OBJECT classes, if you want to use tr in a cpp class use QObject::tr() and lupdate. after this string is moved to QObject context in Linguist and works fine. – Ali Sep 14 '21 at 00:10