Qt Linguist - установить переводчик для файлов приложения Qt *.ui

Я написал крошечный простой пример для изменения языка приложений после выбора языка в меню. Хотя соединение работает (qDebug() печатает хорошие сообщения), оно не меняет текст в моем QLabel. Я создал графический интерфейс с помощью QtDesigner. ПРИМЕЧАНИЕ. Все эти файлы находятся в одном каталоге. Я использую Qt5. Вот мой код:

*.pro:

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = qt_pl_en
TEMPLATE = app


SOURCES += main.cpp\
        mainwindow.cpp

HEADERS  += mainwindow.h

FORMS    += mainwindow.ui

TRANSLATIONS += ic.ts
TRANSLATIONS += se.ts

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QTranslator>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    retranslate();

    QObject::connect(ui->action_Icelandic, SIGNAL(triggered()), this, SLOT(speakIcelandic()));
    QObject::connect(ui->action_Swedish, SIGNAL(triggered()), this, SLOT(speakSwedish()));
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::changeEvent(QEvent* event)
{
    if (event->type() == QEvent::LanguageChange)
    {
        // retranslate designer form
        ui->retranslateUi(this);

        // retranslate other widgets which weren't added in designer
        retranslate();
    }

    // remember to call base class implementation
    QWidget::changeEvent(event);
}

void MainWindow::retranslate()
{
    ui->label->setText(QObject::tr("Hello, world! :-)"));
}

void MainWindow::speakSwedish()
{
    QTranslator translator;
    translator.load("se.qm");
    qApp->installTranslator(&translator);

    ui->retranslateUi(this);

    qDebug() << "Swedish";
}

void MainWindow::speakIcelandic()
{
    QTranslator translator;
    translator.load("ic.qm");
    qApp->installTranslator(&translator);

    ui->retranslateUi(this);

    qDebug() << "Icelandic";
}

mainwindow.h

    #ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    Ui::MainWindow *ui;

    void retranslate();
    void changeEvent(QEvent* event);


private slots:

    void speakSwedish();
    void speakIcelandic();
};

#endif // MAINWINDOW_H

main.cpp

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

ic.ts

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="en_EN">
<context>
    <name>MainWindow</name>
    <message>
        <location filename="mainwindow.ui" line="14"/>
        <source>MainWindow</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="mainwindow.ui" line="27"/>
        <location filename="mainwindow.cpp" line="13"/>
        <source>Hello, world! :-)</source>
        <translation type="unfinished">Halló, heimur! :-)</translation>
    </message>
    <message>
        <location filename="mainwindow.ui" line="42"/>
        <source>File</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="mainwindow.ui" line="60"/>
        <source>&amp;Swedish</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="mainwindow.ui" line="65"/>
        <source>&amp;Icelandic</source>
        <translation type="unfinished"></translation>
    </message>
</context>
</TS>

set.ts

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="en_EN">
<context>
    <name>MainWindow</name>
    <message>
        <location filename="mainwindow.ui" line="14"/>
        <source>MainWindow</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="mainwindow.ui" line="27"/>
        <location filename="mainwindow.cpp" line="13"/>
        <source>Hello, world! :-)</source>
        <translation type="unfinished">Hallå, världen! :-)</translation>
    </message>
    <message>
        <location filename="mainwindow.ui" line="42"/>
        <source>File</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="mainwindow.ui" line="60"/>
        <source>&amp;Swedish</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="mainwindow.ui" line="65"/>
        <source>&amp;Icelandic</source>
        <translation type="unfinished"></translation>
    </message>
</context>
</TS>

mainwindow.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>400</width>
    <height>300</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralWidget">
   <widget class="QLabel" name="label">
    <property name="geometry">
     <rect>
      <x>120</x>
      <y>80</y>
      <width>181</width>
      <height>17</height>
     </rect>
    </property>
    <property name="text">
     <string>Hello, world! :-)</string>
    </property>
   </widget>
  </widget>
  <widget class="QMenuBar" name="menuBar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>400</width>
     <height>25</height>
    </rect>
   </property>
   <widget class="QMenu" name="menuFile">
    <property name="title">
     <string>File</string>
    </property>
    <addaction name="action_Swedish"/>
    <addaction name="action_Icelandic"/>
   </widget>
   <addaction name="menuFile"/>
  </widget>
  <widget class="QToolBar" name="mainToolBar">
   <attribute name="toolBarArea">
    <enum>TopToolBarArea</enum>
   </attribute>
   <attribute name="toolBarBreak">
    <bool>false</bool>
   </attribute>
  </widget>
  <widget class="QStatusBar" name="statusBar"/>
  <action name="action_Swedish">
   <property name="text">
    <string>&amp;Swedish</string>
   </property>
  </action>
  <action name="action_Icelandic">
   <property name="text">
    <string>&amp;Icelandic</string>
   </property>
  </action>
 </widget>
 <layoutdefault spacing="6" margin="11"/>
 <resources/>
 <connections/>
</ui>

person yak    schedule 22.07.2013    source источник


Ответы (2)


это сработало для меня (перевести с английского на португальский)

1) добавить это в main.cpp

 QApplication app(argc, argv);

//Language Translation
//change the prefered language 
QString locale = "pt" // say i am doing Portuguese language translation
QString file= app.applicationDirPath() +"/translation_"+locale;
QTranslator translator;
bool result=translator.load(file);
if ((locale != "en")  && !result )
{
    QMessageBox msgBox;
    msgBox.setText("Unable to load language translation files");
    msgBox.exec();  
}
app.installTranslator(&translator);

2) Скажите, собираетесь ли вы переводить MainWindow.ui

установите флажок Translatable в каждой метке в этом MainWindow.ui с помощью QT Designer. (вам нечего делать в графическом интерфейсе, кроме этого)

3) создайте файл translation_pt.ts, как указано ниже. Не забудьте указать имя класса внутри тегов имен

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS><TS>
	<context>
		<name>MainWindow</name>
		<!-- Dialog Heading -->
		<message>
			<source>Glasses Fitment Details</source>
			<translation>Detalhes de Calibração dos Óculos</translation>
		</message>
		<!-- Fitter -->
		<message>
			<source>Fitter</source>
			<translation>Ajustador</translation>
		</message>
		<message>
			<source>Fitter's Name</source>
			<translation>Nome do Ajustador</translation>
		</message>
   </context>
</TS>

4) добавьте строку ниже в файл .pro

ПЕРЕВОДЫ = translation_pt.ts

5) перейдите в папку установки qt и выполните следующую команду

lrelease "расположение файла .pro, который вы редактировали на шаге 4"

тогда вы получите файл translation_pt.qm в этом месте

6) скопируйте файл translation_pt.qm в место, где запущен ваш двоичный файл

тогда ваш язык в MainWindow.ui будет автоматически переведен с английского на португальский.

Спасибо,

Саман

person Saman    schedule 23.11.2016
comment
Я новичок в этом, поэтому я смотрел на создателя qt, у которого нет всех других атрибутов свойств элемента пользовательского интерфейса, как это видно в дизайнере qt. Чтобы другие видели это, вам нужно развернуть стрелку раскрывающегося списка текстового свойства, чтобы увидеть флажок translatable. - person haxpor; 22.08.2019

Хорошо, ребята, решение проще, чем вы можете себе представить. Добавлять:

QTranslator *translator;

в mainwindow.h

затем в speakIcelandic() и speakSwedish()mainwindow.cpp) просто измените код реализации на:

bool ok = translator->load("se.qm");
qDebug("translation %d", ok);
qApp->installTranslator(translator);

ui->retranslateUi(this);

qDebug() << "Swedish";

Не забудьте добавить translator = new QTranslator(); в конструктор, и все наконец-то заработает!

person yak    schedule 23.07.2013
comment
Здравствуйте, подскажите пожалуйста, где вы определяете qApp? в main.cpp? чем он должен быть глобальным, поскольку мы используем его в mainwindow.cpp ...?? - person nat; 11.01.2017