使用 CMake 构建 Qt Qml 插件

Building Qt Qml Plugin using CMake

我想使用 CMake(而不是 QMake)编译 Qt Qml Plugin,并将此插件添加到某些应用程序。插件和应用程序脚本应该分开 CMakeLists.txt.

文件结构:

CMakeLists.txt
main.cpp
main.qml
qml.qrc
plugin/
    CMakeLists.txt
    MyItem.cpp
    MyItem.h
    Plugin.h
    qmldir

我有一个生成 libmyplugin.dylibqmldir 的脚本 plugin/CMakeLists.txt 并将其放入插件二进制目录的 plugin/MyPlugin 子文件夹中:

plugin/CMakeLists.txt:

cmake_minimum_required(VERSION 3.8)

add_library(myplugin SHARED
    Item.cpp
    Item.h
    Plugin.h
)

set_target_properties(myplugin PROPERTIES
    AUTOMOC TRUE
    LIBRARY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/package/MyPlugin
)

# Copy qmldir file
add_custom_command(
    OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/package/MyPlugin/qmldir
    DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/qmldir
    COMMAND "${CMAKE_COMMAND}" -E copy "${CMAKE_CURRENT_SOURCE_DIR}/qmldir" "${CMAKE_CURRENT_BINARY_DIR}/package/MyPlugin/qmldir"
    COMMENT "Copy qmldir"
)
target_sources(myplugin PRIVATE
    ${CMAKE_CURRENT_BINARY_DIR}/package/MyPlugin/qmldir
)

find_package(Qt5 REQUIRED COMPONENTS Core Qml Quick)
target_link_libraries(viewWorld PUBLIC Qt5::Core Qt5::Qml Qt5::Quick)

现在我需要构建 myplugin 目标 before/after app 目标并将插件文件从 <myplugin binary dir>/plugin 复制到 app 目标二进制文件的位置(以防万一Windows 和 Linux) 或 <app bundle>/Contents/PlugIns(如果是 macOS):

CMakeLists.txt:

cmake_minimum_required(VERSION 3.8)

add_executable(app
    main.cpp
    qml.qrc
)

set_target_properties(app PROPERTIES
    AUTORCC TRUE
)

add_subdirectory(plugin)
add_dependencies(app plugin)
# Needs to copy plugin files...

find_package(Qt5 REQUIRED COMPONENTS Core Qml Quick)
target_link_libraries(viewWorld PUBLIC Qt5::Core Qt5::Qml Qt5::Quick)

只有当插件文件发生变化时,我才需要复制它们。编写将采用 app 目标和 plugin 目标并创建适当依赖项的函数会很棒。

对于我的 Qt 项目和 qml 插件,我使用下一个规则。 win平台下确实如此,希望对你的macOS有所帮助

所有项目的输出目录相同:

set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)

所以所有 sub_directories 与 CMakeLists 和它的项目目标将构建到同一目录中。这对项目 运行 和最终部署很有帮助。

Qml插件我复制到目录

set_target_properties(targetProject PROPERTIES
   RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin/$<CONFIG>/plugins/${QmlPluginName}/)

构建 qml 插件后,我将 qmldir 文件复制到 RUNTIME_OUTPUT_DIRECTORY

add_custom_command(TARGET ${targetProject} POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy
    ${QML_DIR_FILE}
    ${CMAKE_BINARY_DIR}/bin/$<CONFIG>/plugins/${QmlPluginName}/qmldir)

完成这些步骤后,我得到了 hext 目录结构:

/build_dir/bin/Debug/
           |application.exe
           |plugins/
           | |QmlPluginName/
           | | |qmldir
           | | |QmlPluginName.dll

所以在这一步之后不要忘记:

QQmlApplicationEngine engine;
engine.addImportPath("./plugins");    

P.S。对不起我的英语