Qt Quick I18N
为Qt Quick 应用程序生成翻译文件(TS 和 QM)。
运行示例应用程序时,QML Runtime 会根据系统语言,自动从包含主 .qml 文件的i18n
子目录加载翻译文件。
将文本标记为可翻译文本
在Main.qml
文件中,使用qsTr
命令将用户界面文本标记为可翻译文本:
Text { text: qsTr("Hello")
启用翻译
在main.cpp
文件中,使用QQmlApplicationEngine 从包含主 QML 文件的目录中名为i18n
的子目录自动加载翻译文件:
#include <QQmlApplicationEngine> int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); QQmlApplicationEngine engine;
i18n
子目录中的翻译文件名必须以qml_
为前缀。例如,qml_en_AU.ts
。
创建翻译文件
在CMakeLists.txt
文件中添加LinguistTools
模块,作为find_package
命令的值:
find_package(Qt6 REQUIRED COMPONENTS Core Gui Quick Qml LinguistTools)
在qt_add_translations命令中定义要生成的翻译文件:
qt_add_translations(qmli18n RESOURCE_PREFIX /qt/qml/Translated/i18n TS_FILE_BASE qml TS_FILE_DIR i18n )
构建应用程序以生成 TS 和 QM 文件。
注: 在 Android 上,确保将 QM 文件作为资源包含。
添加翻译
要为新语言创建翻译,请将i18n/base.ts复制到i18n / qml_<lang>.ts。您可以使用 Qt Linguist来翻译字符串。
© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.