Qt applications with Cargo

2018-10-30

This blog shows how Qt applications can be built with Cargo. The goal is to make compiling them as simple as installing Qt and running

Rust Qt Binding Generator (Logo by Alessandro Longo)
Rust Qt Binding Generator (Logo by Alessandro Longo)

The crates qrep and mailmodel are examples. You can try qrep with

qrep is a minimal GUI for ripgrep.

qrep
qrep

mailmodel is a proof-of-concept mail reader.

mailmodel
mailmodel

You can get started quickly with your own Rust Qt application by copying the folder templates/qt_quick_cargo from the Rust Qt Binding Generator repository.

Why Cargo?

In previous blogs we built applications with CMake. CMake is probably the most widely used tool to compile Qt software. CMake uses Cargo to build the Rust parts.

CMake is a familiar tool for Qt developers, but not for Rust developers. For them, CMake is an unneeded hurdle. Rust Qt Binding Generator can be used with only Cargo. To do so you use the Rust way of building C++ code: build.rs.

build.rs

build.rs contains Rust code that is compiled and run by Cargo to build an application. Here is a simple build.rs file:

This file is placed directly in your project folder. The last command, compile("my_project"), compiles a library called my_project.

Cargo.toml

build.rs and the name of the library should be added to Cargo.toml:

[package]
name = "my_project"
version = "0.1.0"
build = "build.rs"    # use build.rs for custom build steps
links = "my_project"  # and link to the resulting library

[dependencies]
libc = "0.2"

[build-dependencies]
rust_qt_binding_generator = "0.2"

src/main.rs

main.rs is the entry point for Rust applications. In these applications, two things should happen:

Qt applications have an event loop. Starting this loop requires some C++ code. We start the event loop in a C++ function. The name of the application is passed to this function.

src/main.cpp

The template contains one C++ file. That is usually all you need. But it’s possible to add more C++ files by adding more calls to Build::cpp.

This file loads the GUI from a QML file and starts the event loop.

qml.qrc

Qt applications can contain resources. These are embedded files that are accessible via qrc: URLs. The template application contains two resources: main.qml and MainForm.qml. Other resources such as translations or application icons can be added as well.

Concluding

The option to build Qt applications with Cargo should please Rust programmers. I’ve ported my personal projects to build this way. Using CMake is also still supported and is recommended for C++ projects that currently use CMake and would like to introduce Rust.

This feature is new and not widely tested. Bugs can be filed here.

Comments

Post a comment