11 个版本
使用旧的 Rust 2015
0.3.6 | 2021 年 4 月 4 日 |
---|---|
0.3.5 | 2020 年 1 月 12 日 |
0.3.4 | 2019 年 2 月 25 日 |
0.3.0 | 2019 年 1 月 21 日 |
0.1.1 | 2018 年 10 月 9 日 |
#307 in FFI
35 每月下载量
在 3 crates 中使用
465KB
7K SLoC
Rust Qt Binding Generator
此代码生成器可快速帮助您从 Qt 和 QML 使用 Rust 代码。换句话说,它有助于在 Rust 代码之上创建基于 Qt 的 GUI。
Qt 是一个成熟的跨平台图形用户界面库。Rust 是一种新的编程语言,具有强大的编译时检查和现代语法。
入门
有两个模板项目可帮助您快速入门。一个是用于 Qt Widgets 的,另一个是用于 Qt Quick 的。只需将这些文件夹复制为新项目并开始编码即可。
Qt Widgets (main.cpp) / Qt Quick (main.qml) | ⟵ 手写的 UI 代码 |
src/Binding.h | ⟵ 从 binding.json 生成 |
src/Binding.cpp | |
rust/src/interface.rs | |
rust/src/implementation.rs | ⟵ 手写的 Rust 代码 |
要结合 Qt 和 Rust,在 JSON 文件中编写一个接口。根据该接口,生成器创建 Qt 代码和 Rust 代码。Qt 代码可以直接使用。Rust 代码有两个文件:接口和实现。接口可以直接使用。
{
"cppFile": "src/Binding.cpp",
"rust": {
"dir": "rust",
"interfaceModule": "interface",
"implementationModule": "implementation"
},
"objects": {
"Greeting": {
"type": "Object",
"properties": {
"message": {
"type": "QString",
"write": true
}
}
}
}
}
此文件描述了一个具有一个对象 Greeting
的绑定。 Greeting
有一个属性: message
。它是一个可写属性。
Rust Qt Binding Generator 将从该描述创建绑定源代码
rust_qt_binding_generator binding.json
这将创建四个文件
- src/Binding.h
- src/Binding.cpp
- rust/src/interface.rs
- rust/src/implementation.rs
只有implementation.rs
需要更改。其他文件是绑定。初始时,implementation.rs
使用了一个简单的实现,这里带有一些注释。
use interface::*;
/// A Greeting
pub struct Greeting {
/// Emit signals to the Qt code.
emit: GreetingEmitter,
/// The message of the person.
message: String,
}
/// Implementation of the binding
/// GreetingTrait is defined in interface.rs
impl GreetingTrait for Greeting {
/// Create a new greeting with default data.
fn new(emit: GreetingEmitter) -> Greeting {
Greeting {
emit: emit,
message: "Hello World!",
}
}
/// The emitter can emit signals to the Qt code.
fn emit(&self) -> &GreetingEmitter {
&self.emit
}
/// Get the message of the Greeting
fn message(&self) -> &str {
&self.message
}
/// Set the message of the Greeting
fn set_message(&mut self, value: String) {
self.message = value;
self.emit.message_changed();
}
}
Qt和QML项目的构建块是QObject和模型视图类。rust_qt_binding_generator
读取一个json文件以生成QObject或QAbstractItemModel类,这些类调用生成的Rust文件。对于JSON文件中的每个类型,都会生成一个Rust特质,应该实现这个特质。
这样,Rust代码就可以从Qt和QML项目中调用。
使用Rust的Qt Widgets
下面的C++代码使用了上面编写的Rust代码。
#include "Binding.h"
#include <QDebug>
int main() {
Greeting greeting;
qDebug() << greeting.message();
return 0;
}
使用Rust的Qt Quick
下面的Qt Quick(QML)代码使用了上面编写的Rust代码。
Rectangle {
Greeting {
id: rust
}
Text {
text: rust.message
}
}
演示应用程序
该项目附带一个演示应用程序,展示了一个基于Rust的Qt用户界面。它使用对象、列表和树的所有功能。阅读演示代码是一个很好的入门方式。



Docker开发环境
为了快速开始,项目附带了一个Dockerfile
。您可以使用./docker/docker-bash-session.sh
启动一个带有所需依赖的docker会话。
有关Qt的更多信息
教程
演示
有关Qt的信息
问题
请在KDE问题跟踪器中报告错误和功能请求,产品为"rust-qt-binding-generator"。
依赖关系
~4–6.5MB
~110K SLoC