[CMake] Qt translation handling

Francis Giraldeau francis.giraldeau at gmail.com
Thu Jan 17 11:56:19 EST 2019


Here is a small snipped I wanted to share about generation of qt translation

files.


The Qt translations are managed using two files: ts and qm. The ts files are
edited by translators and updated from source files. Therefore, they must be
added to the repository. To include the translations in the application, qm
binary file is generated. This file is generated in the build tree and must
not be added to the repository.

Qt5 suggests to use qt5_create_translation() macro. However, this macro
regenerate the ts file at build time. It is very inconvenient when working
on multiple branches, because it forces to either commit the modified
translation file or discard the update. Instead, we use a custom target
"make translations" that update ts files only when requested explicitely.

set(TS_FILES
    ${CMAKE_CURRENT_SOURCE_DIR}/translations/app_fr.ts
)
file(GLOB_RECURSE TS_SOURCES "*.cpp" "*.h" "*.ui")
add_custom_target(translations)
foreach(_ts_file ${TS_FILES})

    # generate a sensible name for this translation file
    get_filename_component(_ts_name ${_ts_file} NAME_WE)

    # call lupdate ourselves
    add_custom_command(
        OUTPUT "${_ts_file}"
        DEPENDS ${TS_SOURCES}
        COMMAND ${Qt5_LUPDATE_EXECUTABLE} -recursive
${CMAKE_CURRENT_SOURCE_DIR} -ts ${_ts_file}
    )

    # create a target that depends on the generated files
    add_custom_target(translate_${_ts_name} DEPENDS ${_ts_file})

    # attach the custom target for this ts file to the parent target
    add_dependencies(translations translate_${_ts_name})
endforeach()

# generate qm files
qt5_add_translation(QM_FILES ${TS_FILES})
configure_file(translations.qrc ${CMAKE_CURRENT_BINARY_DIR} COPYONLY)


add_executable(App

    ${QM_FILES}

    ${CMAKE_CURRENT_BINARY_DIR}/translations.qrc

)


Cheers,


Francis

-- 
Francis Giraldeau
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://cmake.org/pipermail/cmake/attachments/20190117/ba694d36/attachment.html>


More information about the CMake mailing list