在https://blog.csdn.net/fengbingchun/category_12172633.html 上有直接通过vs2022建的Console、Widgets、Quick三个工程,这里增加通过CMake构建。
build.sh内容如下:
#! /bin/bashif [ $# != 1 ]; thenecho "Error: requires one parameter: Release or Debug"echo "For example: $0 Debug"exit -1
fiif [ $1 != "Debug" ] && [ $1 != "Release" ]; thenecho "Error: supported parameter values are only Debug or Release: $1"exit -1
firesult_judgment()
{rc=$?if [[ ${rc} != 0 ]]; thenecho -e "\033[0;31mError: there are some errors in the above operation, please check: ${rc}\033[0m"exit ${rc}fi
}build_dir="build"
if [ ! -d ${build_dir} ]; thenmkdir -p ${build_dir}
ficd buildcmake \-G"Visual Studio 17 2022" -A x64 \-DCMAKE_BUILD_TYPE=$1 \-DCMAKE_CONFIGURATION_TYPES=$1 \..
result_judgmentcmake --build . --config $1
result_judgmentecho -e "\033[0;32mbuild finish\033[0m"
CMakeLists.txt内容如下:
cmake_minimum_required(VERSION 3.24.0)
project(Qt_Test)message(STATUS "build type: ${CMAKE_BUILD_TYPE}")
message(STATUS "current source dir: ${CMAKE_CURRENT_SOURCE_DIR}")
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)set(CMAKE_PREFIX_PATH "C:/Qt/6.4.2/msvc2019_64/lib/cmake/Qt6") # Qt6Config.cmake file locationfind_package(Qt6 REQUIRED COMPONENTS Core Gui Widgets Quick)
qt_standard_project_setup()# Widgets_Test
set(SRCS_WIDGETS_PATH ${CMAKE_CURRENT_SOURCE_DIR}/../../demo/Widgets_Test)
set(SRCS_WIDGETS${SRCS_WIDGETS_PATH}/main.cpp${SRCS_WIDGETS_PATH}/Widgets_Test.cpp${SRCS_WIDGETS_PATH}/Widgets_Test.ui
)add_executable(Widgets_Test ${SRCS_WIDGETS})
target_include_directories(Widgets_Test PRIVATE ${SRCS_WIDGETS_PATH})
target_link_libraries(Widgets_Test PRIVATE Qt6::Widgets)
# set_target_properties(Widgets_Test PROPERTIES # no need
# WIN32_EXECUTABLE ON
# MACOSX_BUNDLE ON
# )# Console_Test
set(SRCS_CONSOLE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/../../demo/Console_Test)
aux_source_directory(${SRCS_CONSOLE_PATH} SRCS_CONSOLE)add_executable(Console_Test ${SRCS_CONSOLE})
target_include_directories(Console_Test PRIVATE ${SRCS_CONSOLE_PATH})
target_link_libraries(Console_Test PRIVATE Qt6::Core)# Quick_Test
#set(CMAKE_AUTOMOC ON) # no needset(SRCS_QUICK_PATH ${CMAKE_CURRENT_SOURCE_DIR}/../../demo/Quick_Test)
set(SRCS_QUICK${SRCS_QUICK_PATH}/main.cpp
)add_definitions(-DCMAKE_BUILD_METHOD)add_executable(Quick_Test ${SRCS_QUICK}) # you can also use qt_add_executable
target_link_libraries(Quick_Test PRIVATE Qt6::Gui Qt6::Quick)
#target_sources(Quick_Test PRIVATE ${SRCS_QUICK_PATH}/qml.qrc) # no need
生成的vs2022工程如下:
注:
1.Widgets_Test和Console_Test工程既可以调试运行也可以通过cmd运行;
2.运行Quick_Test需要做些改动:具体原因未知
(1).需要将demo/Quick_Test/main.cpp中的一条语句做调整,如下:
#ifdef CMAKE_BUILD_METHODengine.load(QUrl(QStringLiteral("main.qml"))); // 使用CMakeLists.txt生成工程时需要使用此句
#elseengine.load(QUrl(QStringLiteral("qrc:/main.qml")));
#endif
(2).如果通过打开工程调试运行,需要将demo/Quick_Test下的main.qml和test.jpg拷贝到build目录下,即与Qt_Test.sln同一目录;
(3).如果直接通过cmd运行,需要将main.qml和test.jpg拷贝到Quick_Test.exe同一目录下。通过cmd运行结果如下:
GitHub:https://github.com/fengbingchun/Qt_Test