How to Use CMake with Qt5 and OpenCV 3 Projects

Following a number of questions that appear before me every now and then, I decided to write a post about using CMake to create and build projects using Qt5 and OpenCV 3. For those of you who are qmake fans, using CMake doesn’t mean you can’t use Qt Creator to create and build your projects. In fact, after the release of more recent versions of Qt Creator, CMake support is getting better and better, and it’s fair to say that using CMake with Qt Creator 4.5.1 is almost as easy as using qmake.

Apart from what was said above, CMake supports many of functionalities that do not exist on qmake by default, so it might be even recommended to use CMake instead of qmake in some cases. This might make more sense if we take a look at the following CMake file, which is the most simple form of a CMakeLists.txt file needed to create and run a Qt project with UI files that also uses OpenCV:

#Specify the minimum version of CMake(3.1 is currently recommended by Qt)
cmake_minimum_required(VERSION 3.1)

# Specify project title

# To automatically run MOC when building(Meta Object Compiler)

# To automatically run UIC when building(User Interface Compiler)

# To automatically run RCC when building(Resource Compiler)

# Specify OpenCV folder, and take care of dependenciesand includes
set(OpenCV_DIR "path_to_folder_of_OpenCVConfig.cmake_file")
find_package(OpenCV REQUIRED)

# Take care of Qt dependencies
find_package(Qt5 COMPONENTS Core Gui Widgets REQUIRED)

# add required source, header, uiand resource files
add_executable(${PROJECT_NAME} "main.cpp" "mainwindow.h" "mainwindow.cpp" "mainwindow.ui")

# link required libs
target_link_libraries(${PROJECT_NAME} Qt5::Core Qt5::Gui Qt5::Widgets ${OpenCV_LIBS})

Note that setting CMAKE_AUTOMOC to ON is required if your code uses Qt. Settings CMAKE_AUTOUIC and CMAKE_AUTORCC  to ON is required if your project contains Qt’s UI files (*.ui) and resource (*.qrc) files.

Also, “path_to_folder_of_OpenCVConfig.cmake_file” must be replaced with the folder where OpenCVConfig.cmake and OpenCVConfig-version.cmake files are created automatically when building OpenCV. Otherwise, you’ll face a CMake generate error that says it can’t find OpenCV.

add_executable is quite obvious, and it contains all of your project files (sources, headers and so on).

Finally, target_link_libraries command in the CMake file takes care of making sure that the correct library files are linked when building your project.

Note that this CMakeLists.txt file can be extended a lot to customize even more parts of the building of your Qt+OpenCV project and it should be treated like a minimum required set of commands required for handling such projects.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.