如何讓 CMake 使用 Qt4.8 或 Qt5 有條件地編譯?換句話說,如果 Qt5 可用,則使用 Qt5 進行編譯。否則,如果 Qt4.8 可用,請使用它。
在我的 CMake 中,我有:
find_package(Qt5 COMPONENTS Core Gui Widgets...)
這適用于我的 Qt5 構建,但我如何獲得相同的軟體來構建 Qt4.8?
我需要包含主要版本號的東西,例如:
find_package(Qt $QT_VERSION_MAJOR...)
或使用條件,例如:
result = find_package(Qt 5...)
if (!result) then find_package(Qt4 ...)
或以某種方式檢測當前安裝的 Qt 版本。
對于安裝了 Qt4.8 的機器,我得到的錯誤是(不出所料):
CMake Error at CMakeLists.txt:54 (find_package):
By not providing "FindQt5.cmake" in CMAKE_MODULE_PATH this project has
asked CMake to find a package configuration file provided by "Qt5", but
CMake did not find one.
Could not find a package configuration file provided by "Qt5" with any of
the following names:
Qt5Config.cmake
這里最好的方法是什么?
uj5u.com熱心網友回復:
使用find_package命令NAME選項自動選擇可用的 Qt 版本相當容易。問題是 Qt4 和 Qt5 對相同的模塊有不同的名稱。
# We first try to find the main module of Qt4, Qt5 or Qt6
find_package(QT NAMES Qt4 Qt5 Qt6 REQUIRED)
set(QT Qt${QT_VERSION_MAJOR})
# We prepare lists of modules and libraries for different
# versions of Qt
if (QT_VERSION_MAJOR EQUAL 4)
set(APP_QT_MODULES QtCore QtNetwork QtGui QtXml)
set(APP_QT_TARGETS Qt4::QtCore Qt4::QtNetwork Qt4::QtGui Qt4::QtXml)
else ()
set(APP_QT_MODULES Core Network PrintSupport Widgets Xml)
set(APP_QT_TARGETS ${QT}::Core ${QT}::Network ${QT}::PrintSupport ${QT}::Widgets ${QT}::Xml)
endif ()
# Here everything is simple - find the modules we need.
find_package(${QT} REQUIRED ${APP_QT_MODULES})
. . .
. . .
# And at last don't forget to add libraries.
add_executable(my_app app.cpp main.cpp window.cpp)
target_link_libraries(my_app ${APP_QT_TARGETS})
另一個問題是 Qt 函式也有不同的名稱,例如qt4_add_resources和qt5_add_resources。這是一個很好的理由來懷疑您是否真的需要在您的專案中支持 Qt4。
更新
我們可以制作 Qt 函式別名(就像Qt自 5.15 版以來所做的那樣)。
if (QT_VERSION VERSION_LESS 5.15)
macro(qt_wrap_cpp)
${QT}_wrap_cpp(${ARGV})
endmacro()
macro(qt_add_resources)
${QT}_add_resources(${ARGV})
endmacro()
macro(qt_generate_moc)
${QT}_generate_moc(${ARGV})
endmacro()
endif ()
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/429963.html
上一篇:c qt我可以用多個結構物件填充一個QVariant嗎
下一篇:帶翻譯的QT模型視圖
