Using CMake to build a Qt application

CMake is a really great build tool, and it makes it very easy to use a lot of libraries with it. For example, CMake has a built-in module that helps you to set up a Qt project. Unfortunately, it's a bit tricky to get started with it, so this post provides you a quick getting started guide to create a typical Qt application. For most of the time, we have to deal with three Qt related file types (besides .cpp and .h): .qrc, .ui and .h/.cpp files which contain Q_OBJECT enabled classes.


.qrc contain resources, and are the easiest to handle. The Qt resource compiler (rcc) simply creates a single .cpp file, and puts all resources as static arrays into it. The corresponding CMake function is QT4_ADD_RESOURCES. The first parameter is the output, which you have to add to your source file list.


For the .ui files, the UI-compiler has to be called first (uic) which generates a header file; this header contains all the logic to set up your user interface. You include this generated header in your source files, and use it to display the UI. How does this look like in practice? Well, let's assume we have a file "testDialog.ui", which contains the UI, and we want to implement a dialog using this UI. We create a custom class, for example, TestDialog, which is derived from QDialog. This class is put into TestDialog.h/.cpp, and may look like this:

#include "ui_TestDialog.h"

class TestDialog : public QDialog

    TestDialog ();

public slots:
public signals:

    Ui::TestDialog ui;


The "ui_TestDialog.h" file is generated by the user interface compiler (uic), using the QT4_WRAP_UI command. The output is directly into the output folder, so you should add INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR}) to your project file -- otherwise, the files won't be found. In your dialog constructor, you can init the UI now using:

ui.setupUi (this);

QObject derived

Running the meta-object compiler for QObject derived classes is similar to resources, you add QT4_WRAP_CPP in your CMake file, and just add the generated files to your source files. The input for this function is the header of your class, not the implementation -- even though it's called QT4_WRAP_CPP, you must pass the file containing the declaration; this is usually the header. Those files contain a bunch of functions which are needed for the Qt meta-object system. These are stand-alone .cpp files that you usually never have to look at.


I usually wind up including all generated files to my project, so I can debug into them. To generate clean project files for Visual Studio, you should use source groups (check out the SOURCE_GROUP command) -- be careful though, as the files end up in the current build directory. That's it, you should be ready to create Qt applications with CMake! Feel free to ask questions if something is unclear, so I can update the post.


Comments powered by Disqus