Configuración y primeros pasos

Preparándonos para crear nuestra primera aplicación Kirigami

Instalación de Kirigami

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

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:

KubuntuKDE Neon
sudo apt install build-essential cmake extra-cmake-modules qtbase5-dev qtdeclarative5-dev qtquickcontrols2-5-dev kirigami2-dev libkf5i18n-dev gettext libkf5coreaddons-dev qml-module-org-kde-qqc2desktopstyle
ManjaroArch
sudo pacman -S base-devel extra-cmake-modules cmake qt5-base qt5-declarative qt5-quickcontrols2 kirigami2 ki18n kcoreaddons breeze qqc2-desktop-style
OpenSUSE
sudo zypper install --type pattern devel_C_C++
sudo zypper install cmake extra-cmake-modules libQt5Core-devel libqt5-qtdeclarative-devel libQt5QuickControls2-devel kirigami2-devel ki18n-devel kcoreaddons-devel qqc2-desktop-style
Fedora
sudo dnf groupinstall "Development Tools" "Development Libraries"
sudo dnf install cmake extra-cmake-modules qt5-qtbase-devel qt5-qtdeclarative-devel qt5-qtquickcontrols2-devel kf5-kirigami2-devel kf5-ki18n-devel kf5-kcoreaddons-devel qqc2-desktop-style

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

Si desea compilar Kirigami con Qt6, no es posible en la actualidad en Linux con solo los paquetes de la distribución. En lugar de ello, tendrá que echar mano de kdesrc-build.

Compilación de Kirigami con kdesrc-build

KDE dispone de una herramienta para compilar fácilmente todas sus bibliotecas y programas: kdesrc-build. Se puede usar para compilar Kirigami en Linux y FreeBSD.

For this tutorial, you will need to follow the setup instructions for kdesrc-build but using a ~/kde5 directory instead, then copy the sample KF5 file to your home:

cp ~/kde5/src/kdesrc-build/kdesrc-buildrc-kf5-sample ~/.config/kdesrc-buildrc

After that, you may simply run the following on a terminal:

kdesrc-build kirigami kcoreaddons ki18n breeze plasma-integration qqc2-desktop-style
source ~/kde5/build/kirigami/prefix.sh

And then you may compile your Kirigami projects on the same terminal shell you used to source the prefix file. If you close your terminal, you can simply source the file again to compile your app.

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

After that, you may simply run the following on a terminal:

craft kirigami kcoreaddons ki18n breeze kiconthemes qqc2-desktop-style

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.

Primero creamos nuestra carpeta de proyecto. Vamos a llamar a la nuestra «holamundo».

helloworld/
├── CMakeLists.txt
└── src/
    ├── CMakeLists.txt
    ├── main.cpp
    ├── resources.qrc
    └── contents/
        └── ui/
            └── main.qml

Dentro de esta carpeta vamos a crear la carpeta src/ y CMakeLists.txt. Se suele considerar una buena práctica situar todos los archivos de código fuente principales en una carpeta src/. Nuestra carpeta src/, en cambio, va a contener otra carpeta llamada contents/, que a su vez contiene una carpeta llamada ui/. Ahí es donde vamos a crear nuestros archivos QML.

Esta es una convención de KDE, pero no todos los proyectos de KDE usan esta estructura. Usted es libre de configurar las cosas de una manera diferente, pero deberá tener esto en cuenta al crear los archivos CMakeLists.txt y resources.qrc.

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
// Includes relevant modules used by the QML
import QtQuick 2.15
import QtQuick.Controls 2.15 as Controls
import QtQuick.Layouts 1.15
import org.kde.kirigami 2.20 as Kirigami

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

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

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

main.cpp

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.

main.cpp también es el 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
#include <QApplication>
#include <QQmlApplicationEngine>
#include <QtQml>
#include <QUrl>
#include <QQuickStyle>
#include <KLocalizedContext>
#include <KLocalizedString>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    KLocalizedString::setApplicationDomain("helloworld");
    QCoreApplication::setOrganizationName(QStringLiteral("KDE"));
    QCoreApplication::setOrganizationDomain(QStringLiteral("kde.org"));
    QCoreApplication::setApplicationName(QStringLiteral("Hello World"));

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

    QQmlApplicationEngine engine;

    engine.rootContext()->setContextObject(new KLocalizedContext(&engine));
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

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

    return app.exec();
}

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 this page.

resources.qrc

Our resources.qrc is a Qt Resource file. It contains the list of all QML files as well as other files (like custom icons) that will be included in the binary.

1
2
3
4
5
<RCC>
    <qresource prefix="/">
        <file alias="main.qml">contents/ui/main.qml</file>
    </qresource>
</RCC>

Fíjese en la línea <file alias="main.qml">contents/ui/main.qml</file>. En ella se detallan los archivos QML que se van a incluir en el proceso de compilación. En nuestro caso solo usamos main.qml, pero si necesitamos añadir otro archivo QML a nuestro código, deberíamos asegurarnos de que lo incluimos en el archivo resources.qrc añadiendo otra línea semejante a esta.

This resource file lets us use the "qrc:" + "/main.qml" path in our main.cpp, instead of needing to specify the whole "contents/ui/main.qml" path.

CMakeLists.txt

CMakeLists.txt files are needed to use KDE's build system of choice, CMake. The CMakeLists.txt file in our top-level folder 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
cmake_minimum_required(VERSION 3.16)
project(helloworld)

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

include(KDEInstallDirs)
include(KDECMakeSettings)
include(KDECompilerSettings NO_POLICY_SCOPE)

find_package(Qt${QT_MAJOR_VERSION} REQUIRED NO_MODULE COMPONENTS
    Core
    Quick
    Test
    Gui
    QuickControls2
    Widgets
)

find_package(KF${QT_MAJOR_VERSION} REQUIRED COMPONENTS
    Kirigami2
    I18n
    CoreAddons
)

add_subdirectory(src)

feature_summary(WHAT ALL INCLUDE_QUIET_PACKAGES FATAL_ON_MISSING_REQUIRED_PACKAGES)

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 Qt and KDE Frameworks dependencies are managed with find_package(). You will have to modify these lines and include any additional components that you decide to use during the development of your application.

The final line, add_subdirectory(src), points CMake to the helloworld/src/ directory, where our source code is located. Let's delve into the helloworld/src/CMakeLists.txt file in there.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
add_executable(helloworld)

target_sources(helloworld PRIVATE
    main.cpp
    resources.qrc
)

target_link_libraries(helloworld
    Qt${QT_MAJOR_VERSION}::Quick
    Qt${QT_MAJOR_VERSION}::Qml
    Qt${QT_MAJOR_VERSION}::Gui
    Qt${QT_MAJOR_VERSION}::QuickControls2
    Qt${QT_MAJOR_VERSION}::Widgets
    KF${QT_MAJOR_VERSION}::I18n
)

install(TARGETS helloworld ${KDE_INSTALL_TARGETS_DEFAULT_ARGS})

¡Este es mucho más corto! Repasemos lo que hace:

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

Compilar y ejecutar 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.

If you are running your project on Linux, you will need to specify the place where the program will be installed. To do that, we need to change directories to our helloworld/ folder in our terminal application of choice and run the following commands:

cmake -B build/ -DCMAKE_INSTALL_PREFIX="~/kde5/usr"
cmake --build build/
cmake --install build/

The program will be installed to ~/kde5/usr/bin.

If you are compiling your project with Craft on Windows, you might need to specify a CMake Generator for the first step, depending on whether you are using Visual Studio 2019 (msvc) or MinGW (make) to compile your projects.

Con Visual Studio:

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

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.

Podrá ejecutar el programa «helloworld» con:

helloworld # En Linux
helloworld.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