Qt World Summit 2023: Berlin awaits! Join us now
最新版Qt 6.3已正式发布。 了解更多。
最新バージョンQt6.5がご利用いただけます。 詳細はこちら

Making snippets in Qt documentation compilable

Until now snippets were inserted in a snippet file where each fragment of code was surrounded by (mostly) numeric tags. Invoking them was done by making a \snippet command followed by the path to the snippet file and the tag of the code you wanted to quote.

An example:

\snippet graphicsview.cpp 2

The snippet in the snippet file:

//! [2]
class View : public QGraphicsView
public slots:
void zoomIn() { scale(1.2, 1.2); }
void zoomOut() { scale(1 / 1.2, 1 / 1.2); }
void rotateLeft() { rotate(-10); }
void rotateRight() { rotate(10); }
//! [2]

That snippet file was mostly a cpp or qml file. Snippets can contain syntax errors or typos. They are not supposed to pass the review phase, but if they do those errors will not be picked up by the CI. Making the snippets compilable will avoid that. This is however not possible for snippets in qml since qml at the present time is not compilable.

Making snippets compilable also means that you have to insert code that is only there to in order to have the snippet compilable. Code that is not quoted anywhere, and does not really have a functional meaning. Sometimes even «typedef void» statements, just to get the snippet code compilable. It also means that sometimes a snippet file has to be split up. Some snippet code is really not compilable. The snippet might be very succinct (cf infra), or might involve compiling libraries that maybe will not be compilable on some platforms.

//! [1]
//! [0]
#include <QtQuickTest>
//! [0]
//! [1]

In that case the snippet file is split up where one file still has the original name, and the other, non-compilable one, has _snippet appended to its base name.

For QtSql I had to move all Progresql statements to a non-compilable snippet file. I could compile the Progresql statements on Linux, but there are certainly platforms where they cannot get compiled.

Compilable snippets require a new project file, snippets.pro. Below you can see the project file for QtWidgets:



TARGET = widgets_snippets

QT += widgets printsupport

SOURCES += customviewstyle.cpp \
filedialogurls.cpp \
graphicssceneadditemsnippet.cpp \
graphicsview.cpp \
mdiareasnippets.cpp \

This has already been done for QtWidgets, QtSql, QtTest, QtQuickTest and Qt Network.

One limitation is that we only planned to have snippets compilable for syntax or naming checking. I did no further testing of the executable. In Qt 6 qml will be compilable, which will allow us to use the same snippet checking system for qml.

Blog Topics: