A Simple CMake + Qt Widgets Starter Template

in qt

Starting a new Qt project in Qt creator is a breeze thanks to its built-in templates. But, what about those times you prefer working from terminal or vim?

Here's my starter template for QtWidgets + CMake. Feel free to use and expand for your own needs.

tl;dr

My CMake + Qt Widgets starter template on Github:
https://github.com/ynonp/qt-widgets-template

Or as a zip file:
https://github.com/ynonp/qt-widgets-template/archive/master.zip

Building Instructions

To build the template you'll need to have Qt installed and add Qt cmake definitions to CMAKE_PREFIX_PATH. On my machine I have Qt5.9.1 so I added this line to my bashrc:

export CMAKE_PREFIX_PATH=$HOME/Qt5.9.1/5.9.1/clang_64/lib/cmake/

After CMAKE_PREFIX_PATH is set you can:

cd build
cmake ..
make

And if all goes well you'll get a helloworld binary file in build folder.

The CMakeLists.txt file

The main project definitions file is called CMakeLists.txt. Here's what it looks like:

cmake_minimum_required(VERSION 2.8.11)

project(testproject)

# Find includes in corresponding build directories
set(CMAKE_INCLUDE_CURRENT_DIR ON)
# Instruct CMake to run moc automatically when needed.
set(CMAKE_AUTOMOC ON)

# Find the QtWidgets library
find_package(Qt5Widgets)

set(SOURCES
  src/main.cpp
  src/mainwindow.cpp
)

set(FORMS
  forms/mainwindow.ui
)
qt5_wrap_ui(FORM_H ${FORMS})

# Tell CMake to create the helloworld executable
add_executable(helloworld ${SOURCES} ${FORM_H})

# Use the Widgets module from Qt 5.
target_link_libraries(helloworld Qt5::Widgets)

Adding Files

The list of cpp and ui files is hard-coded in CMakeLists.txt. To add more source files or forms you'll need to modify the list there and add your new files.

The list of modules is specified in the last line of CMakeLists.txt. To add Qt Network module modify it to:

target_link_libraries(helloworld Qt5::Widgets Qt5::Network)

Comments