原文链接:https://www.yuque.com/pikachuhy/cmake/cil1pi
Qt pro配置
去掉一些注释后
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = QtDemo
TEMPLATE = app
DEFINES += QT_DEPRECATED_WARNINGS
SOURCES += \
main.cpp \
widget.cpp
HEADERS += \
widget.h
CMake配置
类似pro文件,也增加QT, TARGET, SOURCES, HEADERS几个变量,只考虑Qt5
cmake_minimum_required(VERSION 3.13)
project(QtDemo)
set(TARGET QtDemo)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_AUTOMOC ON)
set(SOURCES main.cpp widget.cpp)
set(HEADERS widget.h)
set(QT Core Gui Widgets)
find_package(Qt5 REQUIRED ${QT})
add_executable(${TARGET} ${SOURCES} ${HEADERS})
qt5_use_modules(${TARGET} ${QT})
注意到qt5_use_modules这个宏,它可以让我们很方便的使用qt的模块
但是
This macro is obsolete. Use target_link_libraries with IMPORTED targets instead.
(这个宏已经弃用,推荐使用基于TARGET的target_link_libraries)
所以,现在改为基于TARGET的写法
cmake_minimum_required(VERSION 3.13)
project(QtDemo)
set(TARGET QtDemo)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_AUTOMOC ON)
set(SOURCES main.cpp widget.cpp)
set(HEADERS widget.h)
set(QT Core Gui Widgets)
find_package(Qt5 REQUIRED ${QT})
add_executable(${TARGET} ${SOURCES} ${HEADERS})
target_link_libraries(${TARGET}
Qt5::Core
Qt5::Gui
Qt5::Widgets
)
QT这个变量可以设置为哪些值?
以deepin 15.9为例,可以看/usr/lib/x86_64-linux-gnu/cmake这个目录下有哪些以Qt5开头的文件夹,就可以填去掉Qt5前缀后的值
官方的说明
The first requirement when using CMake is to use find_package to
locate the libraries and header files shipped with Qt. These libraries
and header files can then be used to build libraries and applications
based on Qt. The recommended way to use Qt libraries and headers with
CMake is to use the target_link_libraries command. This command
automatically adds appropriate include directories, compile
definitions, the position-independent-code flag, and links to the
qtmain.lib library on Windows.
(首先使用find_package指令找到Qt头文件和库文件的位置,然后用target_link_libraries指令使用Qt的头文件和库文件)
参考:Qt5 CMake Manual
https://doc.qt.io/qt-5/cmake-manual.html
考虑ui文件和qrc资源文件
Qt pro配置
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = QtDemo
TEMPLATE = app
DEFINES += QT_DEPRECATED_WARNINGS
SOURCES += \
main.cpp \
widget.cpp
HEADERS += \
widget.h
FORMS += \
widget.ui
RESOURCES += \
qrc.qrc
CMake配置
加了ui文件和qrc资源文件,要增加对它们的处理
cmake_minimum_required(VERSION 3.13)
project(QtDemo)
set(TARGET QtDemo)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_AUTOUIC ON)
set(SOURCES main.cpp widget.cpp)
set(HEADERS widget.h)
set(FORMS widget.ui)
set(RESOURCES qrc.qrc)
set(QT Core Gui Widgets)
find_package(Qt5 REQUIRED ${QT})
add_executable(${TARGET} ${SOURCES} ${HEADERS} ${FORMS} ${RESOURCES})
target_link_libraries(${TARGET}
Qt5::Core
Qt5::Gui
Qt5::Widgets
)
考虑翻译文件
在我目前找到的资料中,翻译文件的处理一般是这样的
• 翻译文件(ts)放在单独的translations文件夹下
• 调试时不生成翻译二进制文件(qm),Release时通过shell脚本生成qm文件
shell脚本
#!/bin/bash
# this file is used to auto-generate .qm file from .ts file.
# author: shibowen at linuxdeepin.com
ts_list=(`ls translations/*.ts`)
for ts in "${ts_list[@]}"
do
printf "\nprocess ${ts}\n"
lrelease "${ts}"
done