Why don't I need to include QObject to get the tr function in main window?
-
In "mainwindow.cpp" I just write "tr" to get the translation function. But in another file I need to include QObject and then use it like:
#include <QObject> ... QObject::tr("Some text")
Why is this?
@Guerrian
hi
When inside a QObject based class method, its directly available.
( #include <QObject> is from base already,and the tr method can just be called )
When inside class with non QObject base class/global function , youmustcan use
it as any static method and call QObject::tr and include the header.
its explained here
http://doc.qt.io/qt-5/i18n-source-translation.html -
in addition to @mrjj MainWindow class is inherited from QObject. tr() function is method of QObject. From the object oriented principles of inheritance, all the base class functions are available in derived class as well. Hence you don't need QObject::tr() inside the main window class. If you are code is any method of class & if the class is not inherited from Object you need to explicitly call the QObject::tr(...). Hope this clarifies. Also tr() is static function.
-
Hi,
In addition to what my fellows already wrote. You don't need your classes to derive from QObject to give them support for translation. See Translating Non-Qt Classes in the Qt documentation chapter @mrjj linked. This method is cleaner than having unrelated calls to static methods in your code.
In the same document you can also see the use of
QCoreApplication::translate
for code that is outside any class. That again makes things cleaner and clearer.