Skip to main content
Ir al contenido

Kirigami con C++

Create your first Kirigami application with C++

Instalación de Kirigami

Antes de empezar, necesitamos instalar Kirigami en nuestra máquina. Existen tres formas de hacerlo:

If you are on a sufficiently up-to-date distribution such as Debian Testing, latest non-LTS Ubuntu, Fedora, openSUSE Tumbleweed, or Arch, you may install Kirigami from your distribution.

If you are on a not up-to-date distribution such as Debian Stable or LTS Ubuntu, you should use kde-builder for this tutorial. It should use at most 2 GB of storage.

Instalación de Kirigami desde los repositorios de su distribución Linux

Necesitamos un compilador de C++, los paquetes de desarrollo de Qt y Kirigami. Abra una aplicación de terminal y ejecute una de las siguientes líneas, dependiendo de la distribución Linux que esté usando:

logo of Linux operating system KubuntuKubuntulogo of Linux operating system KDE neonKDE Neon
sudo apt install build-essential cmake extra-cmake-modules libkirigami-dev libkf6i18n-dev libkf6coreaddons-dev libkf6iconthemes-dev qt6-base-dev qt6-declarative-dev libkf6qqc2desktopstyle-dev
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

Puede encontrar más información para otras distribuciones aquí.

Uso de 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.

Añada lo siguiente al final de ~/.config/kde-builder.yaml:

project kirigami-tutorial:
  repository: ""
  no-src: true

Instalación de Kirigami con Craft

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

While Craft is also available for Linux and FreeBSD, its intended use is only for AppImages and packaging.

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.

Tras esto, solo tiene que ejecutar lo siguiente en una terminal:

craft kirigami kcoreaddons ki18n breeze kiconthemes qqc2-desktop-style

This will take a long while to finish on first run. If you close your terminal, you can simply run the environment setup file again to compile your app.

Estructura del proyecto

Si bien existen herramientas que pueden configurar fácilmente nuestros archivos, los crearemos manualmente. Esto nos permitirá comprender mejor las piezas que compondrán nuestra nueva aplicación.

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Includes relevant modules used by the QML
import QtQuick
import QtQuick.Layouts
import QtQuick.Controls as Controls
import org.kde.kirigami as Kirigami

// Provides basic features needed for all kirigami applications
Kirigami.ApplicationWindow {
    // Unique identifier to reference this object
    id: root

    width: 400
    height: 300

    // Window title
    // i18nc() makes a string translatable
    // and provides additional context for the translators
    title: i18nc("@title:window", "Hello World")

    // Set the first page that will be loaded when the app opens
    // This can also be set to an id of a Kirigami.Page
    pageStack.initialPage: Kirigami.Page {
        Controls.Label {
            // Center label horizontally and vertically within parent object
            anchors.centerIn: parent
            text: i18n("Hello World!")
        }
    }
}

Aquí es donde manejaremos la interfaz de nuestra aplicación.

Si sabe algo de JavaScript, gran parte de QML le será familiar (aunque tiene sus propias peculiaridades). La documentación de Qt dispone de gran cantidad de material sobre este lenguaje si tiene ganas de probar cosas por su cuenta. A lo largo del curso de estos tutoriales nos vamos a centrar en nuestro código QML, donde podemos usar Kirigami para sacar el máximo provecho del mismo.

Por ahora, centrémonos en Main.qml. Primero [importamos](https:// doc.qt.io/qt-6/qtqml-syntax-imports.html) cierto número de importantes módulos:

  • QtQuick, la biblioteca estándar que usan las aplicaciones en QML.
  • QtQuick Controls, que proporciona cierto número de controles estándares que podemos usar para hacer que nuestras aplicaciones sean interactivas.
  • QtQuick Layouts, que proporciona herramientas para situar componentes dentro de la ventana de la aplicación.
  • Kirigami, que proporciona cierto número de componentes adecuados para crear aplicaciones que funcionan en dispositivos de diferentes formas y tamaños.

Luego llegamos a nuestro elemento base, Kirigami.ApplicationWindow, que proporciona algunas funcionalidades básicas que son necesarias para todas las aplicaciones de Kirigami. Esta es la ventana que contendrá todas nuestras páginas, las secciones principales de nuestra interfaz de usuario.

Luego definimos la propiedad id de la ventana a «root». Los identificadores son útiles porque nos permiten hacer referencia a componentes de una forma única, incluso si tenemos varios del mismo tipo.

También definimos la propiedad title de la ventana con el valor «Hello World». Notará que hemos encerrado la cadena «Hello World» en una función llamada i18nc(), donde detallamos el contexto de la cadena así como la propia cadena de texto.

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
[Desktop Entry]
Name=Kirigami Tutorial
Name[ca]=Guia d'aprenentatge del Kirigami
Name[cs]=Tutoriál Kirigami
Name[eo]=Lernilo pri Kirigami
Name[es]=Tutorial de Kirigami
Name[fr]=Tutoriel pour Kirigami
Name[it]=Esercitazione di Kirigami
Name[nl]=Kirigami handleiding
Name[sl]=Učbenik Kirigami
Name[sv]=Kirigami-handledning
Name[tr]=Kirigami Öğreticisi
Name[uk]=Підручник з Kirigami
Name[zh_TW]=Kirigami 教學
Exec=kirigami-hello
Icon=kde
Type=Application
Terminal=false
Categories=Utility

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
cmake_minimum_required(VERSION 3.20)
project(kirigami-tutorial)

find_package(ECM 6.0.0 REQUIRED NO_MODULE)
set(CMAKE_MODULE_PATH ${ECM_MODULE_PATH})

include(KDEInstallDirs)
include(KDECMakeSettings)
include(KDECompilerSettings NO_POLICY_SCOPE)
include(ECMFindQmlModule)
include(ECMQmlModule)

find_package(Qt6 REQUIRED COMPONENTS
    Core
    Quick
    Test
    Gui
    QuickControls2
    Widgets
)

find_package(KF6 REQUIRED COMPONENTS
    Kirigami
    I18n
    CoreAddons
    QQC2DesktopStyle
    IconThemes
)

ecm_find_qmlmodule(org.kde.kirigami REQUIRED)

add_subdirectory(src)

install(PROGRAMS org.kde.tutorial.desktop DESTINATION ${KDE_INSTALL_APPDIR})

feature_summary(WHAT ALL INCLUDE_QUIET_PACKAGES FATAL_ON_MISSING_REQUIRED_PACKAGES)

El CMakeLists.txt define cómo se compilan los proyectos. La mayor parte de su contenido es solo para iniciar el proyecto. Puede leer una explicación detallada, línea por línea, de lo que hace este archivo CMakeLists.txt aquí.

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 línea que contiene install() le indica a CMake dónde debe instalar el archivo de escritorio.

Let's delve into the kirigami-tutorial/src/CMakeLists.txt file in there.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
add_executable(kirigami-hello)

ecm_add_qml_module(kirigami-hello
    URI
    org.kde.tutorial
)

target_sources(kirigami-hello
    PRIVATE
    main.cpp
)

ecm_target_qml_sources(kirigami-hello
    SOURCES
    Main.qml
)

target_link_libraries(kirigami-hello
    PRIVATE
    Qt6::Quick
    Qt6::Qml
    Qt6::Gui
    Qt6::QuickControls2
    Qt6::Widgets
    KF6::I18n
    KF6::CoreAddons
    KF6::IconThemes
)

install(TARGETS kirigami-hello ${KDE_INSTALL_TARGETS_DEFAULT_ARGS})

Este archivo consta de cinco pasos:

  1. crear un ejecutable
  2. cambiar el ejecutable a un módulo de QML que acepte archivos QML
  3. añadir archivos C++ y QML al ejecutable
  4. enlazar las bibliotecas necesarias para poder lanzar el ejecutable
  5. instalar el ejecutable en el lugar correcto

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().

Ahora que nos hemos encargado de CMake, veamos los archivos a los que vamos a dedicar la mayor parte de nuestro tiempo de trabajo.

main.cpp

El archivo kirigami-tutorial/src/main.cpp maneja la «lógica cliente» de nuestra aplicación. C ++ es útil porque es flexible y rápido, incluso aunque sea más complicado que otros lenguajes de programación.

También funciona como punto de entrada de nuestra aplicación. Las dos partes de nuestro proyecto, el motor y la interfaz del usuario, se configuran y se inician aquí.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <QApplication>
#include <QQmlApplicationEngine>
#include <QtQml>
#include <QUrl>
#include <QQuickStyle>
#include <KLocalizedContext>
#include <KLocalizedString>
#include <KIconTheme>

int main(int argc, char *argv[])
{
    KIconTheme::initTheme();
    QApplication app(argc, argv);
    KLocalizedString::setApplicationDomain("tutorial");
    QApplication::setOrganizationName(QStringLiteral("KDE"));
    QApplication::setOrganizationDomain(QStringLiteral("kde.org"));
    QApplication::setApplicationName(QStringLiteral("Kirigami Tutorial"));
    QApplication::setDesktopFileName(QStringLiteral("org.kde.tutorial"));

    QApplication::setStyle(QStringLiteral("breeze"));
    if (qEnvironmentVariableIsEmpty("QT_QUICK_CONTROLS_STYLE")) {
        QQuickStyle::setStyle(QStringLiteral("org.kde.desktop"));
    }

    QQmlApplicationEngine engine;

    engine.rootContext()->setContextObject(new KLocalizedContext(&engine));
    engine.loadFromModule("org.kde.tutorial", "Main");

    if (engine.rootObjects().isEmpty()) {
        return -1;
    }

    return app.exec();
}

Por ahora, no necesitamos entrar en demasiados detalles con respecto a lo que hace nuestro código de main.cpp, pero su función será significativamente más importante cuando decidamos añadir una funcionalidad más compleja a nuestra aplicación en el futuro.

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.

Por ahora, la parte que nos interesa es esta línea:

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).

Compilar e instalar la aplicación

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 o FreeBSD

Compilación con kde-builder

Asegúrese de haber seguido las instrucciones de Uso de kde-builder.

Compile las dependencias de compilación necesarias con kde-builder, y después compile kirigami-tutorial ejecutando las órdenes siguientes en un terminal:

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

Compilación manual

Cambie los directorios a la carpeta raíz del proyecto y luego ejecute las siguientes órdenes en un terminal:

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

El programa se instalará en ~/.local/bin y su entrada de escritorio en ~/.local/share/applications.

Windows

Si está compilando el proyecto en Windows tras haber configurado Craft, CMake debería detectar automáticamente el compilador correcto:

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

Dependiendo de cómo haya instalado el compilador, es posible que deba usar un generador de CMake para el primer paso, según vaya a usar Visual Studio (msvc) o MinGW (make) para compilar proyectos.

En Visual Studio, dependiendo del compilador que haya seleccionado para instalar, puede ser:

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

O:

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

Con MinGW:

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

En ambos casos, el programa se instalará en C:\CraftRoot\bin.

Si tiene alguna duda sobre el nombre del compilador que se debe usar en la llamada a cmake, ejecute:

cmake -G

Listará todos los generadores disponibles.

Ejecución de la aplicación

Podrá ejecutar el programa kirigami-hello con:

kirigami-hello # En Linux, manualmente
kde-builder --run kirigami-hello # Con kde-builder
kdesrc-build --run --exec kirigami-hello kirigami-tutorial # Con kdesrc-build
kirigami-hello.exe # En Windows

¡Ya está! Ahora verá su primera aplicación de Kirigami aparecer ante sus ojos.

Captura de pantalla de la aplicación de Kirigami generada

Para ejecutar la nueva aplicación QML en modo móvil, puede usar QT_QUICK_CONTROLS_MOBILE=1:

QT_QUICK_CONTROLS_MOBILE=1 kirigami-hello

Si ha compilado el proyecto a mano con CMake y, por algún motivo, quiere desinstalar el proyecto, puede ejecutar:

cmake --build build/ --target uninstall