How to build Qt5 applications with CMake on OpenBSD

If you want to develop a Qt application like me on OpenBSD, you may face the same issue. CMake can’t find the Qt modules.

$ cmake -G Ninja -DCMAKE_BUILD_TYPE=Debug ~/src/happy-qt-hacking
-- The C compiler identification is Clang 8.0.1
-- The CXX compiler identification is Clang 8.0.1
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
CMake Error at CMakeLists.txt:18 (find_package):
  By not providing "FindQt5.cmake" in CMAKE_MODULE_PATH this project has
  asked CMake to find a package configuration file provided by "Qt5", but
  CMake did not find one.

  Could not find a package configuration file provided by "Qt5" with any of
  the following names:

    Qt5Config.cmake
    qt5-config.cmake

  Add the installation prefix of "Qt5" to CMAKE_PREFIX_PATH or set "Qt5_DIR"
  to a directory containing one of the above files.  If "Qt5" provides a
  separate development package or SDK, be sure it has been installed.


-- Configuring incomplete, errors occurred!
See also "/home/rsadowski/build-happy-qt-hacking/CMakeFiles/CMakeOutput.log".

This is simply because OpenBSD does not install the Qt5-CMake modules in /usr/local/lib/cmake/ but in /usr/local/lib/qt5/cmake.

In order for find_package to be successful, Qt 5 must be found below the CMAKE_PREFIX_PATH, or the Qt5_DIR must be set in the CMake cache to the location of the Qt5Config.cmake file.

Qt CMake manual

The easiest way to use fix the issue is to set Qt5_DIR

Qt5_DIR=/usr/local/lib/qt5/cmake cmake -G Ninja -DCMAKE_BUILD_TYPE=Debug ~/src/happy-qt-hacking