Using CMake to build Qt projects for Linux

This tutorial shows how to use CMake to create Qt projects. We will demonstrate how to import the Qt5 package in the CMakeLists.txt file and configure it to automatically invoke Qt tools like moc and uic on a Linux machine. If you don’t have Qt installed on your Linux machine, install it (e.g. by running “sudo apt-get install qt5-default” on Debian-based distros).

Before you begin, install VisualGDB 5.3 or later.

  1. Start Visual Studio and open VisualGDB Linux Project Wizard:01-prjname
  2. Select “New Project -> Use CMake” and check the “Use the advanced CMake Project Subsystem” checkbox:02-cmake
  3. On the next page of the wizard select your Linux computer and click “Next”:03-machine
  4. Proceed with the default “Store files on the remote machine and access them over SSH” setting. This will ensure that IntelliSense will always get the latest versions of the source files:04-directssh
  5. Press “Finish” to create the project. Open the CMakeLists.txt file generated by VisualGDB and add the following lines after the project() line:

    Then save it by pressing Ctrl-S and ensure that CMake (in the VisualGDB CMake Output view) does not report any errors:05-find-qt
  6. Right-click on the CMakeQtDemo target in Solution Explorer and select Add->New Item. Enter the “MainWindow.ui” name (as long as you explicitly enter the “.ui” extension, you can keep “C++ Source File” selected:06-mainwindow
  7. Replace the contents of the MainWindow.ui file with this. Then add MainWindow.h file with the following contents:

    Then add MainWindow.cpp:

    Finally replace the contents of the main CMakeQtDemo.cpp file with this:
  8. If you try building your project now, you should get an error stating that QMainWindow.h is not found:07-missingfile
  9. You can fix this by opening Visual Studio Project Properties for the CMakeQtDemo target and adding “Qt5::Widgets” to “Linked Libraries”: 08-widgets
  10. VisualGDB will automatically update the CMakeLists.txt file. Referencing a library will automatically add include directories exported by it, so your project will now find the QMainWindow file. However, the ui_MainWindow.h file will be missing:09-uic
  11. To fix this, add “set (CMAKE_AUTOUIC ON)” before the “find_package(Qt5 …)” line:10-builtuic
  12. Now you should be able to build the project by pressing Ctrl-Shift-B. Press F5 to start debugging it:11-debug
  13. VisualGDB CMake projects are fully self-contained and can be built on any machine with CMake (all changes made via Visual Studio GUI will be automatically applied to the CMakeLists.txt files). Try opening a terminal in Visual Studio, creating another build directory and invoking cmake <path to source directory> && make manually:build2