背景
版本:
- Clion 2021.3.2
- Qt 5.14
关于Clion的相关博客太少了,Clion +Qt 的文章就更少了。比如,今天想要连接SQLite数据库,但是不知道怎样连接。后面慢慢探索,终于搞懂了。
Clion主要是由CMake去进行项目构建,那么当加入新的模块时,也是在CMakeLists文件里进行添加,对应Qt的Pro文件。
我的Clion版本在创建Qt项目时,会自动生成一个模板。
分析CMakeLists
首先来看这段CMake代码
find_package(Qt5 COMPONENTS
Core
Gui
Widgets
REQUIRED)
add_executable(LoginDialog main.cpp LoginDialog.cpp LoginDialog.h LoginDialog.ui SQLiteClass.cpp SQLiteClass.h)
target_link_libraries(LoginDialog
Qt5::Core
Qt5::Gui
Qt5::Widgets
)
那么我们可以照猫画虎,添加上Sql模块
find_package(Qt5 COMPONENTS
Core
Gui
Widgets
Sql
REQUIRED)
add_executable(LoginDialog main.cpp LoginDialog.cpp LoginDialog.h LoginDialog.ui SQLiteClass.cpp SQLiteClass.h)
target_link_libraries(LoginDialog
Qt5::Core
Qt5::Gui
Qt5::Widgets
Qt5::Sql
)
CMake运行没问题,跑一下,发现程序起不来。而终端信息也没有报错。
接着,再分析下面的CMake代码
if (WIN32)
set(DEBUG_SUFFIX)
set(QT_INSTALL_PATH "${CMAKE_PREFIX_PATH}")
if (NOT EXISTS "${QT_INSTALL_PATH}/bin")
set(QT_INSTALL_PATH "${QT_INSTALL_PATH}/..")
if (NOT EXISTS "${QT_INSTALL_PATH}/bin")
set(QT_INSTALL_PATH "${QT_INSTALL_PATH}/..")
endif ()
endif ()
if (EXISTS "${QT_INSTALL_PATH}/plugins/platforms/qwindows${DEBUG_SUFFIX}.dll")
add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD
COMMAND ${CMAKE_COMMAND} -E make_directory
"$<TARGET_FILE_DIR:${PROJECT_NAME}>/plugins/platforms/")
add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy
"${QT_INSTALL_PATH}/plugins/platforms/qwindows${DEBUG_SUFFIX}.dll"
"$<TARGET_FILE_DIR:${PROJECT_NAME}>/plugins/platforms/")
endif ()
foreach (QT_LIB Core Gui Widgets)
add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy
"${QT_INSTALL_PATH}/bin/Qt5${QT_LIB}${DEBUG_SUFFIX}.dll"
"$<TARGET_FILE_DIR:${PROJECT_NAME}>")
endforeach (QT_LIB)
endif ()
这段代码有段关键的地方,就是最后foreach这里,大意是把相关的dll给拷贝过来,那到这里应该就明白了,我们之前添加的语句没问题,思路正确,只是缺少对应的sql的dll文件。
添加上sql模块
foreach (QT_LIB Core Gui Widgets Sql)
add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy
"${QT_INSTALL_PATH}/bin/Qt5${QT_LIB}${DEBUG_SUFFIX}.dll"
"$<TARGET_FILE_DIR:${PROJECT_NAME}>")
endforeach (QT_LIB)
endif ()
这下运行就没问题啦!