El Kirigami amb Rust
Instal·lació del Kirigami
Abans de començar, haurem d'instal·lar el Kirigami i el Rust a la nostra 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 |
Trobareu més informació sobre les altres distribucions aquí.
Estructura del projecte
Primer crearem la nostra carpeta de projecte (podeu utilitzar les ordres de sota). L'anomenarem kirigami_rust/
. Aquesta serà l'estructura del projecte:
kirigami_rust/
├── CMakeLists.txt
├── Cargo.toml
├── build.rs
├── org.kde.kirigami_rust.desktop
└── src/
├── main.rs
└── qml/
└── Main.qml
This project will use CMake to call Cargo, which in turn will build the project.
About CMake and Cargo
This is not the traditional way of building a Rust project: technically, only Cargo is needed to build it, usually with cargo build
and cargo run
.
For desktop applications however, CMake (or an equivalent like Meson used by GNOME or Just used by COSMIC) is needed to install because Cargo lacks the necessary features to install GUI desktop applications.
The project will be called kirigami_rust
and it will generate an executable called kirigami_hello
.
💡 Consell
Podeu generar ràpidament aquesta estructura de fitxers amb:mkdir -p kirigami_rust/src/qml/
.org.kde.kirigami_rust.desktop
El propòsit principal dels fitxers Desktop Entry és mostrar la vostra aplicació al llançador d'aplicacions en el Linux. Una altra raó per a tenir-los és tenir icones de finestra al Wayland, ja que es requereixen per a dir al compositor «aquesta finestra va amb aquesta icona».
Ha de seguir un esquema de noms DNS invers seguit de l'extensió .desktop
com ara 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.
Ara que ens hem revisat el CMake, vegem els fitxers als quals dedicarem la major part del nostre temps de treball.
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í és on manejarem el frontal de la nostra aplicació.
Si coneixeu alguna cosa de JavaScript, gran part de QML us resultarà familiar (encara que té les seves pròpies peculiaritats). Si teniu ganes de provar alguna cosa pel vostre compte, la documentació de les Qt té una gran quantitat de material sobre aquest llenguatge. Al llarg d'aquestes guies d'aprenentatge, centrarem gran part de la nostra atenció en el codi en QML, on podrem emprar el Kirigami per a aprofitar-lo al màxim.
Per ara, centrem-nos en Main.qml
. Primer importarem diversos mòduls importants:
- QtQuick, la biblioteca estàndard utilitzada en les aplicacions QML.
- QtQuick Controls, que proporciona una sèrie de controls estàndard que podem utilitzar perquè les nostres aplicacions siguin interactives.
- QtQuick Layouts, que proporciona eines per a col·locar els components dins de la finestra de l'aplicació.
- El Kirigami, que proporciona una sèrie de components adequats per a crear aplicacions que funcionen en dispositius de formes i mides diferents.
Nota
Posar els QtQuick Controls i les importacions del Kirigami en espais de noms separats utilitzant la paraula clauas
és una millor pràctica que assegura que cap component amb el mateix nom pugui entrar en conflicte. Podreu trobar diferents noms per als controls QtQuick en els textos, com ara «QQC» o «QQC2». Utilitzarem "Controls" en aquesta guia d'aprenentatge per a més claredat.Després arribem al nostre element base, la Kirigami.ApplicationWindow, que proporciona algunes característiques bàsiques necessàries per a totes les aplicacions escrites amb el Kirigami. Aquesta és la finestra que contindrà cadascuna de les nostres pàgines, les seccions principals de la nostra interfície d'usuari.
Després, establim la propietat id
de la finestra a "root". Els ID són útils perquè ens permeten fer referència de forma única a un component, fins i tot si en tenim diversos del mateix tipus.
També establim la propietat title
de la finestra a "Hola món".
Després establirem la primera pàgina de la nostra pila de pàgines. La majoria de les aplicacions escrites amb el Kirigami estan organitzades com una pila de pàgines, cada pàgina conté els components relacionats adequats per a una tasca específica. Per ara, el mantenim senzill i ens cenyim a una sola pàgina. pageStack és una pila inicialment buida de pàgines proporcionades per Kirigami.ApplicationWindow, i amb pageStack.initialPage: Kirigami.Page{...}
establim la primera pàgina presentada en carregar l'aplicació a una Kirigami.Page. Aquesta pàgina contindrà tot el nostre contingut.
Finalment, incloem en la nostra pàgina un Controls.Label que ens permetrà inserir text a la nostra pàgina. Utilitzarem anchors.centerIn: parent
per a centrar la nostra etiqueta horitzontalment i verticalment dins de l'element pare. En aquest cas, el component principal de la nostra etiqueta és Kirigami.Page. L'últim que hem de fer és configurar el text: text: "Hello World!"
.
Compilar i instal·lar l'aplicació
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.
Run the following:
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.
Obriu l'entrada de menu i heus aquí! Ara veureu aparèixer la vostra primera aplicació escrita amb el Kirigami.
Per a executar la nova aplicació QML en mode de mòbil, podeu utilitzar QT_QUICK_CONTROLS_MOBILE=1
:
QT_QUICK_CONTROLS_MOBILE=1 kirigami_hello
Si heu compilat el projecte manualment amb el CMake i per algun motiu voleu desinstal·lar el projecte, podeu executar:
cmake --build build/ --target uninstall