Kirigami con Rust
Instalación de Kirigami
Antes de empezar, necesitamos instalar Kirigami y Rust nuestra máquina.
sudo pacman -S cargo cmake extra-cmake-modules kirigami breeze qqc2-desktop-style | |
sudo zypper install cargo cmake kf6-extra-cmake-modules kf6-kirigami-devel qt6-quickcontrols2-devel kf6-qqc2-desktop-style | |
sudo dnf install cargo cmake extra-cmake-modules kf6-kirigami2-devel kf6-qqc2-desktop-style |
Further information for other distributions can be found in Installing build dependencies.
Estructura del proyecto
Primero creamos nuestra carpeta de proyecto (puede usar las órdenes siguientes). Vamos a llamar a la nuestra kirigami_rust/. Esta será la estructura del proyecto:
kirigami_rust/
├── CMakeLists.txt
├── Cargo.toml
├── build.rs
├── org.kde.kirigami_rust.desktop
└── src/
├── main.rs
└── qml/
└── Main.qmlEste proyecto usará CMake para llamar a Cargo, que se encargará de compilar el proyecto.
Acerca de CMake y Cargo
Esta no es la forma tradicional de compilar un proyecto de Rust: técnicamente, solo se necesita Cargo para compilarlo, normalmente con cargo build y cargo run.
No obstante, para instalar aplicaciones de escritorio se necesita CMake (o un equivalente como Meson, usado por GNOME, o Just, usado por COSMIC), ya que Cargo carece de la funcionalidad necesaria para instalar aplicaciones de escritorio con interfaz de usuario.
El proyecto se llamará kirigami_rust y generará un ejecutable llamado kirigami_hello.
💡 Consejo
Puede crear esta estructura rápidamente con:mkdir -p kirigami_rust/src/qml/.org.kde.kirigami_rust.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.kirigami_rust.desktop:
| |
CMakeLists.txt
The CMakeLists.txt file is going to be used to run Cargo and to install the necessary files together with our application. It also provides certain quality of life features, such as making sure that Kirigami is installed during compilation and to signal Linux distributions to install the necessary dependencies with the application.
| |
The first thing we do is add KDE's Extra CMake Modules (ECM) to our project so we can use ecm_find_qml_module to check that Kirigami is installed when trying to build the application, and if it's not, fail immediately. Another useful ECM feature is ECMUninstallTarget, which allows to easily uninstall the application with CMake if desired.
We also use CMake's find_package() to make sure we have qqc2-desktop-style, KDE's QML style for the desktop. This is one of the two reasons we use CMake in this tutorial.
Typically Rust projects are built with Cargo, and it won't be different here. We create a target that will simply run Cargo when run, and mark it with ALL so it builds by default. Cargo will build the executable inside CMake's binary directory (typically build/).
For more information about CMake, targets, and the binary directory, see Building KDE software manually.
After this, we simply install the kirigami_rust executable generated by Cargo in the binary directory and install it to the BINDIR, which is usually /usr/bin, /usr/local/bin or ~/.local/bin. We also install the necessary desktop file to APPDIR, which is usually /usr/share/applications or ~/.local/share/applications. This is the second reason we use CMake in this tutorial.
For more information about where KDE software is installed, see Building KDE software manually: The install step.
Ahora que nos hemos encargado de CMake, veamos los archivos a los que vamos a dedicar la mayor parte de nuestro tiempo de trabajo.
Cargo.toml
Next we have a very straightforward Cargo.toml:
| |
It consists of project metadata and a list of dependencies that will be pulled automatically by Cargo, namely cxx and cxx-qt, which are necessary to run Qt applications written in Rust.
build.rs
Where in C++ you'd typically register QML elements with QML_ELEMENT and ecm_add_qml_module using declarative registration, with Rust you'll need to declare it in a build script build.rs file:
| |
This is necessary to make the QML file available in the entrypoint for our application, main.rs.
src/main.rs
The file kirigami_rust/src/main.rs initializes the project and then loads the QML file, which will consist of the user interface for the application.
| |
The first part that is marked with the #[cxx_qt::bridge] Rust macro just creates a dummy QObject out of a dummy Rust struct. This is needed just to complete the use of QmlModule in the previous build script build.rs. This will play a larger part in a future tutorial teaching how to expose Rust code to QML, but for now you can ignore it.
After this starts the important part:
Lines 12-13 import the needed Qt libraries exposed through cxx-qt.
We first create a new instance of a QApplication, then perform a few integrations in lines 20-26.
Then comes the part that actually creates the application window:
| |
The long URL qrc:/qt/qml/org/kde/tutorial/src/qml/Main.qml corresponds to the Main.qml file according to the Qt Resource System, and it follows this scheme: <resource_prefix><import_URI><QML_dir><file>.
In other words: the default resource prefix qrc:/qt/qml/ + the import URI org/kde/tutorial (set in build.rs, separated by slashes instead of dots) + the QML dir src/qml/ + the QML file Main.qml.
src/qml/Main.qml
| |
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, which provides a number of components suited for creating applications that work across devices of different shapes and sizes.
Nota
Putting the QtQuick Controls and Kirigami imports into separate namespaces using theas keyword is a best practice that ensures no components with the same name can conflict. You might see different names for QtQuick Controls in the wild, such as "QQC" or "QQC2". We will be using "Controls" in this tutorial for clarity.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.
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.
We also set the window title property to "Hello World".
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: "Hello World!".
Compilar e instalar la aplicación
You should find the generated executable kirigami_hello under build/debug/kirigami_hello and you may run it directly or with cargo run, but it will lack a Window icon. To address this, we'll install the application first.
Ejecute lo siguiente:
cmake -B build --install-prefix ~/.local
cmake --build build/
cmake --install build/With the first command, CMake will search for Kirigami and qqc2-desktop-style.
With the second command, CMake will build the kirigami_rust target, which just calls cargo build --target-dir build/. This step will take a while to complete, but the next time you repeat the second CMake command it will be faster or you will not need to compile at all.
In the third step, CMake will install the executable kirigami_hello under ~/.local/bin/kirigami_hello and the desktop file under ~/.local/share/applications, and a new entry named "Kirigami Tutorial in Rust" will appear on your menu.
Open the menu entry and voilà! Now you will see your very first Kirigami app appear before your very own eyes.

Para ejecutar la nueva aplicación QML en modo móvil, puede usar QT_QUICK_CONTROLS_MOBILE=1:
QT_QUICK_CONTROLS_MOBILE=1 kirigami_helloSi ha compilado el proyecto a mano con CMake y, por algún motivo, quiere desinstalar el proyecto, puede ejecutar:
cmake --build build/ --target uninstall