We have an example which uses cmake to build the qt5 project: use-vtk-in-qt-widget-example

But that workflow seems a cheat, I used Qt Creator to create a qmake project and wrote CMakeLists.txt later, regards it as a project file and reopen that project again.
I read the introduction of cmake in the book Foundations Of Qt Development.
It is suitable for Qt4, but that sounds interesting for me to write a single CMakeLists.txt to build a whole qt5 project.
So I create a traditional Qt GUI project that contains a ui file and a qrc file.
The following images show all files in this simple project.

Our leading role CMakeLists.txt is here.

cmake_minimum_required(VERSION 2.8)


set( QT_QMAKE_EXECUTABLE "/Users/weiyang/Downloads/Qt5.11.2/5.11.2/clang_64/bin/qmake" )

set( Qt5_DIR "/Users/weiyang/Downloads/Qt5.11.2/5.11.2/clang_64/lib/cmake/Qt5" )

set( Qt5Core_DIR "/Users/weiyang/Downloads/Qt5.11.2/5.11.2/clang_64/lib/cmake/Qt5Core" )

set( SOURCES main.cpp mainwindow.cpp )

set( HEADERS mainwindow.h )

set( UIS mainwindow.ui )

set( QRCs mainwindow.qrc )

find_package( Qt5 COMPONENTS widgets REQUIRED )


qt5_wrap_ui( UI_HEADERS ${UIS} )

qt5_add_resources( QRC_Srcs ${QRCs} )

include_directories( ${CMAKE_CURRENT_BINARY_DIR} )

add_definitions( ${QT_DEFINITIONS} )


qt5_use_modules( ${PROJECT_NAME} Core Gui Widgets )

target_link_libraries( ${PROJECT_NAME} ${QT_LIBRARIES} )

We need to set the Qt5 directory which is under lib/camke.
The statement set( CMAKE_AUTOMOC ON ) can help us to generate moc files from class that inherited QObject and use the signal-slot mechanism.
qt5_wrap_ui( UI_HEADERS ${UIS} ) tells cmake that all header files generated from UI files consist of a set:  ${UI_HEADERS}
add_definitions( ${QT_DEFINITIONS} ) helps to set up preprocessor definitions of QT.
qt5_use_modules( ${PROJECT_NAME} Core Gui Widgets ) means our project uses qt module Core, Gui and Widgets.
Actually, we just need widgets module at this situation.
Finally target_link_libraries makes CMake link all qt libraries that need and generate an executable file.
Relevant code link: https://github.com/theArcticOcean/qtLib/tree/master/cmakeTest


Leave a Reply

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

You cannot copy content of this page