Qt 使用 CMake: ui_mainwindow.h: 没有那个文件或目录

Qt using CMake: ui_mainwindow.h: No such file or directory

我将 Qt 与 CMake 结合使用,因为 CMake 与我团队的工作相集成比我自己的工作更容易。我经常遇到类似

的错误
ui_*.h: No such file or directory

通常当我的项目已经有一个 ui_*.h 文件开始时,它只会修改那个 .h 文件。我确实在我的 CMake 文件中使用了以下命令,所以它应该用适当的 ui_*.h 文件包装我的 .ui 文件。

qt4_wrap_ui (mainwindow  mainwindow.ui)
target_linked_library (mainwindow ${QT_LIBRARIES})

但有时这不起作用,我必须完全重建整个 ui_*.h 文件。我做错了什么?

快速解决方案是使用 UIC。在 bash 中导航到包含 *.ui 文件和 运行 的目录(对于 mainwindow.ui 示例)

uic mainwindow.ui -o ui_mainwindow.h

然后将新生成的 ui_mainwindow.h 文件移动到您的构建目录。

mv ui_mainwindow.h ../build_Qt_4_8_5-Debug/

您应该不会再看到 'No such file or directory' 错误,并且可以自信地继续使用 CMake 在 Qt 世界中找到许多其他美妙的错误。

如果我没记错的话,您实际上必须像这样将 UI 文件添加到 add_executable(...)

qt4_wrap_ui(UI_HEADERS mainwindow.ui ...) # Add all UI files here like you've done it
...
add_executable(${PROJECT_NAME} ${SRC} ${UI_HEADERS}) # Add them to the executable
...

毕竟 UI 文件实际上被转换为头文件和源文件,自然必须与其余代码一起编译。

对于将来遇到此问题的任何人。我几乎按照这里的演示。

http://doc.qt.io/qt-5/cmake-manual.html

添加以下行到 CMakeLists.txt 应该可以解决这个问题。

set(CMAKE_AUTOUIC ON)

来自

的 CMake 文档

https://cmake.org/cmake/help/v3.0/prop_tgt/AUTOUIC.html

AUTOUIC is a boolean specifying whether CMake will handle the Qt uic code generator automatically, i.e. without having to use the QT4_WRAP_UI() or QT5_WRAP_UI() macro. Currently Qt4 and Qt5 are supported.

一个小提示,此 属性 在 CMake 版本 3.0.2+ 中可用。所以在这之下,@rbaleksandar 的解决方案应该更合适。

希望对您有所帮助。

Building with CMake好像有错误

if(CMAKE_VERSION VERSION_LESS "3.7.0")
    set(CMAKE_INCLUDE_CURRENT_DIR ON)
endif()

像这样删除 CMakeLists.txt 中的 if

set(CMAKE_INCLUDE_CURRENT_DIR ON)

这适用于我的 CMake 3.12.1 和 Windows 10 系统。

当 ui 文件存储在不同的位置时,CMAKE_AUTOUIC_SEARCH_PATHS 可以设置为包括自定义位置,这样 CMAKE_AUTOUIC 选项将找到 ui文件。