cmake 生成qt uic文件配置cmakelist
时间: 2024-12-13 17:13:36 浏览: 9
当你需要在CMake项目中集成Qt的UI界面文件(`.ui`),并且想通过CMake自动生成Qt资源文件(`.qrc`)以及相关的`.cpp`和`.h`头文件,可以按照以下步骤进行配置:
1. 首先,在你的CMakeLists.txt文件中,你需要找到Qt的安装路径,通常在包含`QT5_DIR`或`find_package(Qt5Widgets REQUIRED)`这样的行。确保已经正确设置了Qt的模块(例如`Qt5Widgets`)。
```cmake
find_package(Qt5Widgets REQUIRED)
include(${QT5_USE_FILE})
```
2. 使用`QT_QMAKE_EXECUTABLE`变量找到QMake工具:
```cmake
execute_process(COMMAND ${QT_QMAKE_EXECUTABLE} -query QT_INSTALL_UIC EXECUTE_OUTPUT_VARIABLE UI_COMPILER_PATH)
message(STATUS "Found Qt UIC at: ${UI_COMPILER_PATH}")
```
3. 创建一个函数来处理`.ui`文件到`.cpp`文件的转换:
```cmake
function(generate_ui_files INPUT.ui OUTPUT.cpp OUTPUT.h)
get_filename_component(ui_path ${INPUT} PATH)
get_filename_component(input_name ${INPUT} NAME_WE)
execute_process(
COMMAND ${UI_COMPILER_PATH} ${INPUT}
WORKING_DIRECTORY ${ui_path}
OUTPUT_VARIABLE ui_generated_code
ERROR_VARIABLE error_output
OUTPUT_STRIP_TRAILING_WHITESPACE
)
file(WRITE "${ui_path}/${output_name}.cpp" "${ui_generated_code}")
add_custom_command(
OUTPUT ${OUTPUT.cpp}
COMMAND ${CMAKE_COMMAND} -E copy_if_different ${ui_path}/${input_name}.h ${OUTPUT.h}
DEPENDS ${INPUT}
VERBATIM
)
endfunction()
```
4. 现在,你可以调用这个函数处理每个`.ui`文件:
```cmake
generate_ui_files("path/to/your/ui_file.ui" "path/to/your/generated/cpp_file.cpp" "path/to/your/generated/header_file.h")
```
5. 最后,记得将生成的源文件添加到项目的源码列表中,并链接到Qt库:
```cmake
add_executable(your_target_name main.cpp ${OUTPUT.cpp})
target_link_libraries(your_target_name Qt5Widgets)
```
阅读全文