Earlier implementing Cmake I had an error related *.ui file. Whenever I built my project using Qt/console, the build was successfull but when I executed it, it pointed to file mainwindow.h indicating ‘ui_mainwindow.h’ no such file or directory.
Yesterday night when I was trying to solve this, I thought to try up a simple example for generating Cmake for Qt project, as earlier I tried for project that had no .*ui files. What I did was opened Qt creator, created new project. Whenever we create a new project in Qt, the files mentioned below are automatically generated and when it is executed it shows a simple window.
1) <project_name>.pro
2)mainwindow.h
3)mainwindow.cpp
4)main.cpp
5)mainwindow.ui
What I was to do was to build the project through cmake and not through .pro file. I made no changes to these automatically generated files but just created a new file CmakeLists.txt.
#INCORRECT CODE
project(Cmake)
find_package(Qt5Widgets)
set(CMAKE_AUTOMOC ON)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
QT5_WRAP_CPP(Cmake_hdr_moc mainwindow.h)
QT5_WRAP_UI(Cmake_form_hdr mainwindow.ui)
add_library(mainwindow ${Cmake_hdr_moc} ${Cmake_form_hdr})
qt5_use_modules(mainwindow Widgets)
add_executable(Cmake main.cpp mainwindow)
qt5_use_modules(Cmake Core Gui Widgets)
And I used the above code, again got the same error.
But today I found what was going wrong. I went through all the links that Sir posted on GD, even 2-3 more and tried to understand them deeply and finally I got the solution and the project executed successfully with the Cmake.
Below is the correct version of script:
cmake_minimum_required(VERSION 2.8)
project(Cmake)
find_package(Qt5Widgets)
set(CMAKE_AUTOMOC ON)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
QT5_WRAP_UI(Cmake_form_hdr mainwindow.ui)
add_library(mainwindow mainwindow.cpp ${Cmake_form_hdr})
qt5_use_modules(mainwindow Widgets)
add_executable(Cmake main.cpp)
target_link_libraries (Cmake mainwindow)
qt5_use_modules(Cmake Core Gui Widgets)
What I found was:
1)The source was wrong in add_executable
directive.
Instead of:
add_executable(Cmake
We need to do this:
add_executable(Cmake main.cpp)
target_link_libraries (Cmake mainwindow)
2) And one more mistake is missing *.cpp
file in the add_library
directive:
add_library(mainwindow mainwindow.cpp ${Cmake_hdr_moc})
3) Even I found that it is not necessary to use QT5_WRAP_CPP with Automock isn’t neccessary.