本页内容

支持运行时语言切换的本地化时钟

本示例演示了在CMake中使用 Qt 翻译和本地化功能的最佳实践, Qt Quick,特别是如何在运行时更改应用程序的语言。该示例在较简单的“本地化时钟示例”基础上进行了扩展。

有关翻译 Qt 应用程序的更多信息,请参阅《Qt Linguist 》手册。

用户界面

该示例以系统所设的区域设置和语言显示当前的时间和日期。用户界面文本还支持以下语言的本地化:英语、德语、法语、西班牙语、意大利语、日语、韩语、葡萄牙语、阿拉伯语和中文。用户还可以通过菜单按钮选择不同的语言和区域设置。

该应用程序的英文版本:

英文数字时钟的截图

在运行时更改语言后的德语版本:

德语数字时钟的截图

实现

该应用程序由四个部分组成:

CMakeLists.txt

CMake 的集成方式与“本地化时钟”示例中的CMake 集成方式相同。更多详细信息请参阅该页面。

main.cpp

应用程序的起点,负责加载 QML 模块。

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    QQmlApplicationEngine engine;
    QObject::connect(
            &engine, &QQmlApplicationEngine::objectCreationFailed, &app,
            [](const QUrl &) { QCoreApplication::exit(-1); }, Qt::QueuedConnection);
    engine.loadFromModule("qtexamples.localizedclockswitchlocale", "Main");
    return app.exec();
}
翻译管理器 (translator.h, translator.cpp)

TranslatorManager 是一个 QML 单例类,用于在运行时管理语言和区域设置的切换。该类的核心方法是 `TranslatorManager::switchLanguage()`,该方法接受一个表示语言代码的字符串。

虽然该方法标记为Q_INVOKABLE ,但TranslatorManager类声明时使用了QML_ELEMENT 和QML_SINGLETON。这使得该方法可从QML中直接调用;另请参阅Main.qml。

voidTranslatorManager::switchLanguage(constQString&lang)
{
    QLocale locale(lang);
    QLocale::setDefault(locale);
    qApp->removeTranslator(&m_translator); // not necessary from Qt 6.10
   if(m_translator.load(locale, "clock"_L1, "_"_L1, ":/i18n/"_L1)
       && qApp->installTranslator(&m_translator)) {
        m_engine.retranslate();
    }else{
        qWarning("Could not load translation to %s!", qPrintable(locale.name()));
    }
}
运行时更新翻译

切换语言时,会移除之前的翻译(QCoreApplication::removeTranslator()),并加载(QTranslator::load())和安装(QCoreApplication::installTranslator())所选语言的新翻译。随后,QQmlEngine::retranslate() 会触发对 QML 文档中字符串的重新翻译。

更新日期和时间格式

更改语言还可能影响日期和时间的显示方式。例如,如果系统中的QLocale 将“en”对应于“en_US”区域设置,将“de”对应于“de_DE”区域设置:

  • 应用程序初始加载时,国家代码默认为“US”。
  • 根据美国区域设置规范,日期以MM/DD/YYYY格式显示,时间采用 12 小时制。
  • 将语言切换为德语后,由于“de_DE”是德语的首选区域设置,因此国家将更改为德国。
  • 根据德国的惯例,日期将显示为DD.MM.YYYY格式,并采用 24 小时制。

切换语言后,应用程序会使用QLocale::setDefault() 根据所选语言更新其QLocale 。在表示时间时,Date.toLocaleTimeString() 函数会根据应用程序的区域设置对时间和日期进行本地化处理(参见Main.qml)。

Main.qml

主 QML 文件定义了应用程序的用户界面。该界面显示时间、日期以及秒数计数器。关于基本翻译(窗口标题)和复数处理(秒数),请参阅“本地化时钟”示例。

从Menu 中选择一项后,会调用TranslatorManager.switchLanguage() 并传入相应的语言代码。此调用还会自动重新翻译可翻译文本(参见“翻译管理器”)。不过,当语言发生变化时,我们仍需调用updateClock() ,以将时间显示格式更新为新的本地化格式。

        ListModel {
            id: languageModel
            ListElement { name: "English"; code: "en" }
            ListElement { name: "Deutsch"; code: "de" }
            ListElement { name: "العربية"; code: "ar" }
            ListElement { name: "한국어"; code: "ko" }
            ListElement { name: "中文"; code: "zh" }
            ListElement { name: "日本語"; code: "ja" }
            ListElement { name: "Français"; code: "fr" }
            ListElement { name: "Italiano"; code: "it" }
            ListElement { name: "Español"; code: "es" }
            ListElement { name: "Português"; code: "pt" }
        }
        Menu {
            id: languageMenu
            width: languageButton.width
            Repeater {
                model: languageModel
                delegate: MenuItem {
                    required property string name
                    required property string code
                    text: name
                    onTriggered: {
                        TranslatorManager.switchLanguage(code)
                        root.selectedLanguage = name
                        root.updateClock()
                    }
                }
            }
        }

示例项目 @ code.qt.io

© 2026 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.