我想使用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
我有一个脚本plugin/CMakeLists.txt
,该脚本生成libmyplugin.dylib
和qmldir
并将其放入插件二进制目录的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
目标之前/之后构建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
目标并创建适当依赖项的函数将是非常棒的。
答案 0 :(得分:1)
对于我的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)
因此,所有带有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)
完成此步骤后,我将获得以下目录结构:
/build_dir/bin/Debug/
|application.exe
|plugins/
| |QmlPluginName/
| | |qmldir
| | |QmlPluginName.dll
因此,在执行此步骤后,请不要忘记:
QQmlApplicationEngine engine;
engine.addImportPath("./plugins");
P.S。对不起,我的英语