Skip to main content
Skip to content

Kirigami with Rust

Create your first Kirigami application with Rust

Installing Kirigami

Before getting started, we will need to install Kirigami and Rust on our machine.

logo of Linux operating system ManjaroManjarologo of Linux operating system Arch LinuxArch
sudo pacman -S cargo cmake extra-cmake-modules kirigami breeze qqc2-desktop-style
logo of Linux operating system openSUSEOpenSUSE
sudo zypper install cargo cmake kf6-extra-cmake-modules kf6-kirigami-devel qt6-quickcontrols2-devel kf6-qqc2-desktop-style
logo of Linux operating system FedoraFedora
sudo dnf install cargo cmake extra-cmake-modules kf6-kirigami2-devel kf6-qqc2-desktop-style

Further information for other distributions can be found here.

Project structure

First we create our project folder (you can use the commands below). We are going to call ours kirigami_rust/. This will be the project's structure:

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.

The project will be called kirigami_rust and it will generate an executable called kirigami_hello.

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:

1
2
3
4
5
6
7
[Desktop Entry]
Name=Kirigami Tutorial in Rust
Exec=kirigami_hello
Icon=kde
Type=Application
Terminal=false
Categories=Utility

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
cmake_minimum_required(VERSION 3.28)

project(kirigami_rust)

find_package(ECM 6.0 REQUIRED NO_MODULE)
set(CMAKE_MODULE_PATH ${ECM_MODULE_PATH})
include(KDEInstallDirs)
include(ECMUninstallTarget)

include(ECMFindQmlModule)
ecm_find_qmlmodule(org.kde.kirigami REQUIRED)
find_package(KF6 REQUIRED COMPONENTS QQC2DesktopStyle)

add_custom_target(kirigami_rust
    ALL
    COMMAND cargo build --target-dir ${CMAKE_CURRENT_BINARY_DIR}
)

install(
    PROGRAMS ${CMAKE_CURRENT_BINARY_DIR}/debug/kirigami_hello
    DESTINATION ${KDE_INSTALL_BINDIR}
)

install(FILES org.kde.kirigami_rust.desktop DESTINATION ${KDE_INSTALL_APPDIR})

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.

Now that CMake has been taken care of, let's look at the files we are going to spend the majority of our time working with.

Cargo.toml

Next we have a very straightforward Cargo.toml:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
[package]
name = "kirigami_hello"
version = "0.1.0"
authors = [ "Konqi the Konqueror <konqi@kde.org>" ]
edition = "2021"
license = "GPLv3"

[dependencies]
cxx = "1.0.95"
cxx-qt = "0.7"
cxx-qt-lib = { version="0.7", features = ["qt_full"] }
cxx-qt-lib-extras = "0.7"

[build-dependencies]
# The link_qt_object_files feature is required for statically linking Qt 6.
cxx-qt-build = { version = "0.7", features = [ "link_qt_object_files" ] }

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
use cxx_qt_build::{CxxQtBuilder, QmlModule};

fn main() {
    CxxQtBuilder::new()
        .qml_module(QmlModule {
            uri: "org.kde.tutorial",
            qml_files: &["src/qml/Main.qml"],
            rust_files: &["src/main.rs"],
            ..Default::default()
        })
        .build();
}

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.

 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
#[cxx_qt::bridge]
mod ffi {
    extern "RustQt" {
        #[qobject]
        type DummyQObject = super::DummyRustStruct;
    }
}

#[derive(Default)]
pub struct DummyRustStruct;

use cxx_qt_lib::{QGuiApplication, QQmlApplicationEngine, QQuickStyle, QString, QUrl};
use cxx_qt_lib_extras::QApplication;
use std::env;

fn main() {
    let mut app = QApplication::new();
    let mut engine = QQmlApplicationEngine::new();

    // To associate the executable to the installed desktop file
    QGuiApplication::set_desktop_file_name(&QString::from("org.kde.kirigami_rust"));
    // To ensure the style is set correctly
    let style = env::var("QT_QUICK_CONTROLS_STYLE");
    if style.is_err() {
        QQuickStyle::set_style(&QString::from("org.kde.desktop"));
    }

    if let Some(engine) = engine.as_mut() {
        engine.load(&QUrl::from("qrc:/qt/qml/org/kde/tutorial/src/qml/Main.qml"));
    }

    if let Some(app) = app.as_mut() {
        app.exec();
    }
}

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:

28
29
30
    if let Some(engine) = engine.as_mut() {
        engine.load(&QUrl::from("qrc:/qt/qml/org/kde/tutorial/src/qml/Main.qml"));
    }

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

 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
// 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
    title: "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: "Hello World!"
        }
    }
}

Here's where we will be handling our application's frontend.

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, the standard library used in QML applications.
  • 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".

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

Compiling and installing the application

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.

Open the menu entry and voilà! Now you will see your very first Kirigami app appear before your very own eyes.

Screenshot of the generated Kirigami application

To run the new QML application in mobile mode, you can use 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