Skip to content

Commit 701404f

Browse files
WIP add book entry for instantiating in Rust
1 parent 8f56704 commit 701404f

File tree

3 files changed

+36
-0
lines changed

3 files changed

+36
-0
lines changed
+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
<!--
2+
SPDX-FileCopyrightText: 2025 Klarälvdalens Datakonsult AB, a KDAB Group company <[email protected]>
3+
SPDX-FileContributor: Ben Ford <[email protected]>
4+
5+
SPDX-License-Identifier: MIT OR Apache-2.0
6+
-->
7+
8+
# Instantiating `QObject`s directly in Rust
9+
10+
Your `QObject` types will most likely be instantiated via QML, but it is possible to create them in Rust via a template.
11+
By adding
12+
13+
```rust
14+
#[namespace = "rust::cxxqtlib1"]
15+
unsafe extern "C++" {
16+
include!("cxx-qt-lib/common.h");
17+
18+
#[cxx_name = "make_unique"]
19+
#[doc(hidden)]
20+
fn myobject_make_unique() -> UniquePtr<MyObject>;
21+
}
22+
```
23+
24+
You can directly create an instance of your object wrapped in a `UniquePtr` within Rust, should you wish.

book/src/getting-started/1-qobjects-in-rust.md

+2
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,8 @@ In comparison to a normal opaque CXX class, the mapping between the `QObject` su
7070

7171
The `QObject` subclass is its own type in Rust, as well as in C++.
7272
When such a `QObject` is instantiated, it will always also construct an instance of the Rust `struct`.
73+
These `QObject`s can also be constructed via a `UniquePtr<YourObject>` directly in rust, but this is a less common use case,
74+
see [here](../concepts/instantiating_in_rust.md) for more information.
7375
The `QObject` can then refer to the underlying Rust `struct` for property access.
7476
Any behavior of this `QObject` subclass will also be defined in Rust, e.g. using the [`#[qinvokable]`](../bridge/extern_rustqt.html#invokables) attribute.
7577
The Rust implementation also has access to the underlying Rust `struct` to modify any Rust data.

examples/qml_minimal/rust/src/cxxqt_object.rs

+10
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,15 @@ pub mod qobject {
3333
#[namespace = "my_object"]
3434
type MyObject = super::MyObjectRust;
3535
}
36+
37+
#[namespace = "rust::cxxqtlib1"]
38+
unsafe extern "C++" {
39+
include!("cxx-qt-lib/common.h");
40+
41+
#[cxx_name = "make_unique"]
42+
#[doc(hidden)]
43+
fn myobject_make_unique() -> UniquePtr<MyObject>;
44+
}
3645
// ANCHOR_END: book_rustobj_struct_signature
3746

3847
// ANCHOR: book_rustobj_invokable_signature
@@ -50,6 +59,7 @@ pub mod qobject {
5059
}
5160

5261
// ANCHOR: book_use
62+
use crate::cxxqt_object::qobject::myobject_make_unique;
5363
use core::pin::Pin;
5464
use cxx_qt_lib::QString;
5565
// ANCHOR_END: book_use

0 commit comments

Comments
 (0)