mbjoe mbjoe - 1 year ago 155
C++ Question

tr() function not working anymore migrating from Qt 4 to Qt 5

I have an application where the translator is installed successfully in the usual way:

bool bSuccess = qApp->installTranslator(m_translator);

is a pointer to a class derived from

When the application is compiled with Qt 4.7.4 all the following instructions work fine:

  1. QString qTranslString = m_translator->translate("", "string_to_be_translated");

  2. QString qTranslString = QCoreApplication::translate("", "string_to_be_translated");

  3. QString qTranslString = tr("string_to_be_translated");

But when the same application, same project settings, is compiled with Qt 5.2.1, on Windows or Linux, only number 1 is working. The other two are not calling the translate method of

Here is a minimal example for reproducing the problem:


greaterThan(QT_MAJOR_VERSION, 4) {
QT += widgets

TARGET = minimalpbm

SOURCES += main.cpp
HEADERS += mytranslator.h


#include <QTranslator>

class MyTranslator : public QTranslator

explicit MyTranslator(QObject *parent = 0);

bool isEmpty() const;
QString translate(const char *context, const char *sourceText, const char *comment = 0) const;



#include <QApplication>
#include <QMainWindow>
#include "mytranslator.h"

MyTranslator::MyTranslator(QObject *parent) : QTranslator(parent)


bool MyTranslator::isEmpty() const
return false;

QString MyTranslator::translate(const char* /*context*/, const char* sourceText, const char* /*comment*/) const
QString translation;

(void) sourceText;

translation = "Window Title"; // No matter what the source text is we return the same translation for test

return translation;

int main(int argc, char *argv[])
QApplication qA(argc, argv);

QMainWindow qW; // Create main window

MyTranslator *m_translator = new MyTranslator(&qW); // Install translator

qW.setWindowTitle(qW.tr("ST_TITLE")); // Set title
qW.show(); // Show main window

return qA.exec(); // Main event loop

With Qt4 the window title is "Window Title",
with Qt5 the window title is "ST_TITLE".

Any hints?
Thank you very much in advance!

Answer Source

Does MyTranslator::translate still override a QTranslator virtual method? When reading QT 5.2.0 documentation, the method you want to override was removed. I would suggest to try to override the translate method with 4 parameters instead of 3, so translate(const char *context, const char *sourceText, const char *disambiguation = Q_NULLPTR, int n = -1) const. Also put the override keyword behind it, so that the compiler will warn you for such issues.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download