Configuración y primeros pasos
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
- Uso de kde-builder
- Instalación de Kirigami con Craft
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:
ManjaroArch | sudo pacman -S base-devel extra-cmake-modules cmake kirigami ki18n kcoreaddons breeze kiconthemes qt6-base qt6-declarative qqc2-desktop-style |
OpenSUSE | 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 |
Fedora | sudo dnf groupinstall "Development Tools" "Development Libraries" sudo dnf install 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 |
Further information for other distributions can be found here.
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.
Add the following at the end of your ~/.config/kde-builder.yaml
:
project kirigami-tutorial:
no-src: true
⏳ With kdesrc-build...
Click here to know how this was done with kdesrc-build
This step used to be done by writing to ~/.config/kdesrc-buildrc
instead with a different syntax:
# after include ${module-definitions-dir}/kf6-qt6.ksb
module kirigami-tutorial
no-src
end module
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.
Tras esto, solo tiene que ejecutar lo siguiente en una 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.
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.
Consejo
Puede crear esta estructura rápidamente con:
mkdir -p kirigami-tutorial/src
touch kirigami-tutorial/{CMakeLists.txt,org.kde.tutorial.desktop}
touch kirigami-tutorial/src/{CMakeLists.txt,main.cpp,Main.qml}
Nota
In case you want to automatically build the project with kde-builder, custom module name should be the same as the project root folder (in our case it will be "kirigami-tutorial"), otherwise you would need to customize thesource-dir
or dest-dir
for the module. We will assume the path to your main.cpp
will be $HOME/kde/src/kirigami-tutorial/src/main.cpp
.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, que proporciona cierto número de componentes adecuados para crear aplicaciones que funcionan en dispositivos de diferentes formas y tamaños.
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.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.
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.
Nota
Las funciones i18n() hacen que nuestra aplicación sea más fácil de traducir, ya que devuelven una versión de la cadena proporcionada en el idioma del usuario (si la aplicación ha sido traducida a dicho idioma). Si un usuario inglés vería el título de nuestra ventana como «Hello World», un usuario español vería «Hola, mundo».
i18nc() builds on the i18n()
function by allowing developers to provide some context to translators working on the app. Here we clarify that the UI component is the title of the application window, so we have included the string "@title:window" before "Hello World". See the Ki18n Programmer's guide for more details.
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
:
|
|
Nota
Window and taskbar icons will work in a Wayland session only if apps' desktop files are placed in~/.local/share/applications
or /usr/share/applications
. To get icons working in this tutorial, either copy the app's desktop file there or switch to a development session as instructed in kde-builder tutorial. Some KDE applications might have working icons if they were already installed on the system.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.
|
|
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.
The line with install()
tells CMake where to install the desktop file.
Let's delve into the kirigami-tutorial/src/CMakeLists.txt
file in there.
|
|
This file consists of five steps:
- create an executable
- change the executable into a QML module that accepts QML files
- add C++ and QML files to the executable
- link the libraries necessary for the executable to run
- install the executable to the right place
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
The file kirigami-tutorial/src/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.
It also functions as the entrypoint to our application. The two parts of our project, the backend and the user interface, are both set up and started here.
|
|
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.
Uso de temas en Windows
Pulse aquí para leer más
The application needs to set its icon theme, QStyle, and QtQuick Controls style to Breeze in order to show up on Windows. To learn more about it, see Figuring out main.cpp.
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.
For now, the part that interests us is this line:
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).
El método antiguo
You might encounter this alternative way to load QML files in real code!
The old method of loading QML files had some disadvantages and after Qt6 it became excessively verbose:
engine.load(QUrl(QStringLiteral("qrc:/qt/qml/org/kde/tutorial/qml/Main.qml")));
This Qt resource URI above follows the pattern <resource_prefix><import_URI><optional_QML_dir><file>
. In this case:
- resource prefix = default / in Qt5, /qt/qml in Qt6
- import URI = /org/kde/tutorial, which matches the URI org.kde.tutorial
- optional QML dir = /qml, necessary if the QML files are stored in a directory called qml/
- file = the QML file
Compiling and installing the application
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
Compiling with kde-builder
Make sure you have followed the instructions in Using kde-builder.
Compile the necessary build dependencies with kde-builder, then compile kirigami-tutorial
by running the following commands in a terminal:
kde-builder kirigami ki18n kcoreaddons breeze kiconthemes qqc2-desktop-style
kde-builder kirigami-tutorial
Compiling manually
Change directories to the project's root folder, then run the following command in a terminal:
cmake -B build/
cmake --build build/
cmake --install build/ --prefix "$HOME/.local"
The program will be installed to $HOME/.local/bin
and its desktop entry to $HOME/.local/share/applications
.
Windows
If you are compiling your project on Windows after having set up Craft, CMake should automatically detect the right compiler:
cmake -B build/
cmake --build build/
cmake --install build/
Depending on how you installed the compiler, you might need to specify a CMake Generator for the first step, depending on whether you are using Visual Studio (msvc) or MinGW (make) to compile your projects.
If Visual Studio, depending on the compiler you chose to install, it might be:
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
.
If you ever get in doubt as to the name of the compiler that should be used in the cmake
call, run:
cmake -G
It will list all available generators.
Ejecución de la aplicación
You can then run the kirigami-hello
program with:
kirigami-hello # En Linux, manualmente
kde-builder --run kirigami-hello # With kde-builder
kdesrc-build --run --exec kirigami-hello kirigami-tutorial # With kdesrc-build
kirigami-hello.exe # En Windows
¡Ya está! Ahora verá su primera aplicación de Kirigami aparecer ante sus ojos.
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
Nota
La próxima vez que quiera crear los archivos y las carpetas necesarios, puede usar KAppTemplate o KDevelop para generar automáticamente un proyecto adecuado con el que empezar. Están disponibles en los repositorios de las principales distribuciones. Estas aplicaciones también generarán archivos que contienen metadatos de AppStream y un archivo .desktop
que contiene información sobre cómo se debe mostrar la aplicación en un lanzador de aplicaciones de Linux.
Gracias a la magia de CMakeLists, también puede usar un IDE, como KDevelop o QtCreator, para desarrollar esta aplicación dentro de un entorno confortable con el mínimo esfuerzo.