Skip to main content
Aller directement au contenu

Kirigami avec le langage C++

Create your first Kirigami application with C++

Installation de Kirigami

Avant de commencer, nous devrons installer Kirigami sur notre machine. Il y a trois façons de le faire :

Installation de Kirigami à partir des dépôts de votre distribution Linux.

We need a C++ compiler, Qt development packages, and Kirigami. Open a terminal application and run one of the following, depending on which Linux distribution you are using:

logo of Linux operating system ManjaroManjarologo of Linux operating system Arch LinuxArch
sudo pacman -S base-devel extra-cmake-modules cmake kirigami ki18n kcoreaddons breeze kiconthemes qt6-base qt6-declarative qqc2-desktop-style
logo of Linux operating system openSUSEOpenSUSE
sudo zypper install cmake kf6-extra-cmake-modules kf6-kirigami-devel kf6-ki18n-devel kf6-kcoreaddons-devel kf6-kiconthemes-devel qt6-base-devel qt6-declarative-devel qt6-quickcontrols2-devel kf6-qqc2-desktop-style
logo of Linux operating system FedoraFedora
sudo dnf install @development-tools @development-libs cmake extra-cmake-modules kf6-kirigami2-devel kf6-ki18n-devel kf6-kcoreaddons-devel kf6-kiconthemes-devel qt6-qtbase-devel qt6-qtdeclarative-devel qt6-qtquickcontrols2-devel kf6-qqc2-desktop-style

Further information for other distributions can be found here.

Utilisation du module « kde-builder »

Set up your development environment with kde-builder. That will give you the necessary development tools and underlying libraries, and build the KDE Frameworks from scratch.

Create a folder ~/kde/src/kirigami-tutorial. In that folder you will place the source code files from this tutorial.

Ajouter ceci à la fin de votre fichier ~/.config/kde-builder.yaml :

project kirigami-tutorial:
  no-src: true

Installation de Kirigami avec Craft

KDE has a custom tool to easily install most of its libraries and programs: Craft. It can be used to install Kirigami on Linux, FreeBSD, Windows, Android and macOS.

You will need to follow the setup instructions for Craft. By the end of the setup, you should have run an environment setup file (craftenv.ps1 or craftenv.sh), which will give you a terminal shell where you will be compiling your Kirigami application.

Après cela, vous pouvez simplement exécuter ce qui suit dans un terminal :

craft kirigami kcoreaddons ki18n breeze kiconthemes qqc2-desktop-style

Si vous fermez votre terminal, vous pouvez simplement exécuter le fichier de configuration de l'environnement à nouveau pour compiler votre application.

Structure du projet

Bien qu'il existe des outils qui permettent de configurer facilement nos fichiers, nous allons les créer manuellement. Cela nous permettra de mieux comprendre les éléments qui vont constituer notre nouvelle application.

First we create our project folder (you can use the commands below). We are going to call ours kirigami-tutorial/.

kirigami-tutorial/
├── CMakeLists.txt
├── org.kde.tutorial.desktop
└── src/
    ├── CMakeLists.txt
    ├── main.cpp
    └── Main.qml

Within this folder we are going to create a src/ folder and CMakeLists.txt. It is generally considered good practice to place all our main C++ code files in a src/ folder. We also put the Main.qml file in it since it will be run together with the executable.

Main.qml

C'est ici que nous allons gérer l'interface utilisateur de notre application.

If you know some Javascript, then much of QML will seem familiar to you (though it does have its own peculiarities). Qt's documentation has an extensive amount of material on this language if you feel like trying something on your own. Over the course of these tutorials we will be focusing much of our attention on our QML code, where we can use Kirigami to get the most out of it.

For now, let's focus on Main.qml. First we import a number of important modules:

  • QtQuick, la bibliothèque standard utilisée dans les applications QML.
  • QtQuick Controls, which provides a number of standard controls we can use to make our applications interactive.
  • QtQuick Layouts, which provides tools for placing components within the application window.
  • Kirigami, which provides a number of components suited for creating applications that work across devices of different shapes and sizes.

We then come to our base element, Kirigami.ApplicationWindow, which provides some basic features needed for all Kirigami applications. This is the window that will contain each of our pages, the main sections of our UI.

We then set the window's id property to "root". IDs are useful because they let us uniquely reference a component, even if we have several of the same type.

We also set the window title property to "Hello World". You'll notice that we have wrapped our "Hello World" string in a function called i18nc(), where we detail the context of the string as well as the string itself.

We then set the first page of our page stack. Most Kirigami applications are organised as a stack of pages, each page containing related components suited to a specific task. For now, we are keeping it simple, and sticking to a single page. pageStack is an initially empty stack of pages provided by Kirigami.ApplicationWindow, and with pageStack.initialPage: Kirigami.Page {...} we set the first page presented upon loading the application to a Kirigami.Page. This page will contain all our content.

Finally, we include in our page a Controls.Label that lets us place text on our page. We use anchors.centerIn: parent to center our label horizontally and vertically within our parent element. In this case, the parent component of our label is Kirigami.Page. The last thing we need to do is set its text: text: i18n("Hello World!").

org.kde.tutorial.desktop

The primary purpose of Desktop Entry files is to show your app on the application launcher on Linux. Another reason to have them is to have window icons on Wayland, as they are required to tell the compositor "this window goes with this icon".

It must follow a reverse-DNS naming scheme followed by the .desktop extension such as org.kde.tutorial.desktop:

CMakeLists.txt

CMakeLists.txt files are needed to use KDE's build system of choice, CMake. Our kirigami-tutorial/CMakeLists.txt file is going to specify some of our application's characteristics. It also includes some of the dependencies we need in order to compile our project.

The CMakeLists.txt defines how to build your projects. Most of the content here is just to bootstrap your project. You can read a line-by-line, in-depth explanation of what this CMakeLists file does here.

The most important thing to keep in mind is that the C++ build dependencies of Qt and KDE Frameworks are managed with find_package() and QML runtime dependencies are managed with ecm_find_qml_module(). You will have to modify these lines and include any additional components that you decide to use during the development of your application.

The line with add_subdirectory(src) points CMake to the kirigami-tutorial/src/ directory, where our source code is located.

La ligne avec install() indique à CMake où installer le fichier de bureau.

Plongeons dans le fichier `kirigami-tutorial/src/CMakeLists.txt' qui s'y trouve.

Ce fichier se compose de cinq étapes :

  1. créer un exécutable
  2. modifier l'exécutable en un module QML acceptant les fichiers QML
  3. ajouter des fichiers en C++ et QML à l'exécutable
  4. lier les bibliothèques nécessaires à l'exécution du programme
  5. installer l'exécutable au bon endroit

Next time you need to add more QML files, add them to the existing ecm_target_qml_sources() call. C++ files that use the QML_ELEMENT keyword which we will see later in the tutorial can be added using target_sources().

Maintenant que « CMake » a été pris en charge, regardons les fichiers avec lesquels nous allons travailler la majorité de notre temps.

main.cpp

The file kirigami-tutorial/src/main.cpp handles the "business logic" of our application. C++ is handy because it is flexible and fast, even if it is more involved than other programming languages.

It also functions as the entrypoint to our application. The two parts of our project, the backend and the user interface, are both set up and started here.

For now, we don't need to go into too much detail regarding what our main.cpp code does, but its role will grow significantly more important once we decide to add more complex functionality to our application in the future.

If you want to get ahead, you can read more about how this main.cpp works in Figuring out main.cpp.

If you want to see a few ways on how the C++ code can be improved, like using KAboutData for translatable application metadata, be sure to check our KXmlGui tutorial.

Pour l'instant, la partie qui nous intéresse est cette ligne :

engine.loadFromModule("org.kde.tutorial", "Main");

The first argument is the URI set in kirigami-tutorial/src/CMakeLists.txt, and the second argument is the name of the QML module we want to use (Main, coming from the name of our Main.qml file, which needs to start with an uppercase letter).

Compilation et installation de l'application

We are almost at the finish line. The last thing we need to do is build and run our application. Doing so will depend on which platform you are on.

Linux ou FreeBSD

Compilation avec le module « kde-builder »

Assurez-vous d'avoir suivi les instructions sur l'utilisation du module « kde-builder ».

Compile the necessary build dependencies with kde-builder, then compile kirigami-tutorial by running the following commands in a terminal:

kde-builder kirigami ki18n kcoreaddons breeze kiconthemes qqc2-desktop-style
kde-builder kirigami-tutorial

Compilation de façon manuelle

Modifiez les dossier dans le dossier racine du projet, puis exécutez la commande suivante dans un terminal :

cmake -B build/ --install-prefix ~/.local
cmake --build build/
cmake --install build/

Le programme sera installé à l'emplacement ~/.local/bin et son entrée de bureau à ~/.local/share/applications.

Fenêtres

If you are compiling your project on Windows after having set up Craft, CMake should automatically detect the right compiler:

cmake -B build/
cmake --build build/
cmake --install build/

Depending on how you installed the compiler, you might need to specify a CMake Generator for the first step, depending on whether you are using Visual Studio (msvc) or MinGW (make) to compile your projects.

Si dans Visual Studio, en fonction du compilateur que vous avez choisi d'installer, cela peut être :

cmake -B build/ -G "Visual Studio 16 2019"

Ou :

cmake -B build/ -G "Visual Studio 17 2022"

Si MinGW :

cmake -B build/ -G "MinGW Makefiles"
cmake --build build/
cmake --install build/

Dans les deux cas, le programme sera installé dans le dossier C:\CraftRoot\bin.

En cas de doute comme sur le nom du compilateur devant être utilisé dans l'appel cmake, lancez la commande :

cmake -G

Il énumérera tous les générateurs disponibles.

Exécution de l'application

Vous pouvez ensuite exécuter le programme « kirigami-hello » avec :

kirigami-hello # Sous Linux, manuellement
kde-builder --run kirigami-hello # Avec le module « kde-builder »
kdesrc-build --run --exec kirigami-hello kirigami-tutorial # Avec le module « kdesrc-build »
kirigami-hello.exe # Sous Windows

Voilà ! Vous allez voir apparaître maintenant votre toute première application avec Kirigami de vos propres yeux.

 ! Une capture d'écran de l'application générée avec Kirigami

Pour exécuter la nouvelle application QML en mode mobile, vous pouvez utiliser QT_QUICK_CONTROLS_MOBILE=1 :

QT_QUICK_CONTROLS_MOBILE=1 kirigami-hello

If you have compiled the project manually with CMake and for some reason you'd like to uninstall the project, you can run:

cmake --build build/ --target uninstall