本来用qmake使用pro文件很简单的一件事,结果用cmake折腾了半天。
何必呢~
这是我的
cmake_minimum_required(VERSION 3.16)
project(testQml3_6 VERSION 0.1 LANGUAGES CXX)
set(CMAKE_AUTOMOC ON)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
find_package(Qt6 6.2 COMPONENTS Quick REQUIRED LinguistTools)
set(OUR_TS_FILES testQml3_6_zh_CN.ts testQml3_6_de.ts)
qt_add_executable(apptestQml3_6
main.cpp
${OUR_TS_FILES}
)
qt_create_translation(QM_FILES ${CMAKE_SOURCE_DIR} ${OUR_TS_FILES})
qt_add_qml_module(apptestQml3_6
URI testQml3_6
VERSION 1.0
QML_FILES main.qml
)
qt_add_lupdate(apptestQml3_6 TS_FILES ${OUR_TS_FILES})
qt_add_lrelease(apptestQml3_6
TS_FILES ${OUR_TS_FILES}
QM_FILES_OUTPUT_VARIABLE qm_files)
qt_add_resources(apptestQml3_6 "translations"
PREFIX "/"
BASE "${CMAKE_CURRENT_BINARY_DIR}"
FILES "${QM_FILES}")
set_target_properties(apptestQml3_6 PROPERTIES
MACOSX_BUNDLE_GUI_IDENTIFIER my.example.com
MACOSX_BUNDLE_BUNDLE_VERSION ${PROJECT_VERSION}
MACOSX_BUNDLE_SHORT_VERSION_STRING ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}
MACOSX_BUNDLE TRUE
WIN32_EXECUTABLE TRUE
)
target_link_libraries(apptestQml3_6
PRIVATE Qt6::Quick)
install(TARGETS apptestQml3_6
BUNDLE DESTINATION .
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR})
要改四个地方
1, 添加 LinguistTools
2,添加ts文件的包含
3,创建ts文件
4,将生成的翻译好的 qm 文件放到资源目录下
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QLocale>
#include <QTranslator>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QTranslator translator;
const QStringList uiLanguages = QLocale::system().uiLanguages();
for (const QString &locale : uiLanguages) {
const QString baseName = "testQml3_6_" + QLocale(locale).name();
// if (translator.load(":/i18n/" + baseName)) {
// app.installTranslator(&translator);
// break;
// }
if (translator.load(":/" + baseName)) {
app.installTranslator(&translator);
break;
}
}
QQmlApplicationEngine engine;
const QUrl url(u"qrc:/testQml3_6/main.qml"_qs);
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine.load(url);
QString t_str = QObject::tr("hello4");
return app.exec();
}
项目多执行几次Cmake和构建,不然可能刷新不好。
更新ts文件
就是将代码中 tr(“xxxx”) 、qsTr(“yyyyy”) 更新到ts文件中。
发布ts文件
就是将ts文件生成对应的qm文件。
直接从Qt Creator中是发布不了的,应该是bug吧。(菜单栏: Tools>External>Linguist>ReleaseTranslations)
提示:
(在网上也没搜到原因)
两种方法:
1,通过命令行
lrelease testQml3_6_zh_CN.ts
2,在项目上右击选择"构建“”