|
| 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,ignore |
| 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. |
| 25 | +The included header file contains some wrapper templates for constructing `unique_ptr<T>`, `shared_ptr<T>` and `*T`. |
| 26 | +By exposing this to the bridge with the correct namespace, constructing these structs is possible in Rust. |
| 27 | +These helper methods live in cxx-qt-lib, and thus need to be included, and this is also why the namespace is necessary. |
| 28 | +These are helper functions defined by CXX-Qt, and are ***Not the same as*** `std::make_unique`, etc... |
| 29 | + |
| 30 | +## Passing Parameters |
| 31 | + |
| 32 | +You can also supply the constructor with parameters via these helper methods, |
| 33 | +but you should ensure that any constructors with different arguments have different names in Rust, via renaming. |
| 34 | + |
| 35 | +```rust,ignore |
| 36 | +#[namespace = "rust::cxxqtlib1"] |
| 37 | +unsafe extern "C++" { |
| 38 | + include!("cxx-qt-lib/common.h"); |
| 39 | +
|
| 40 | + #[rust_name = "new_my_object_with_parent"] |
| 41 | + fn make_unique(parent: *mut QObject) -> UniquePtr<MyObject>; |
| 42 | + |
| 43 | + // Overloading without the parent parameter |
| 44 | + #[rust_name = "new_my_object"] |
| 45 | + fn make_unique() -> UniquePtr<MyObject>; |
| 46 | +} |
| 47 | +``` |
| 48 | + |
| 49 | +## Possible Methods |
| 50 | + |
| 51 | +| Name | C++ Return Type | Rust Return Type | |
| 52 | +|---------------|-----------------|------------------| |
| 53 | +| `make_unique` | `unique_ptr<T>` | `UniquePtr<T>` | |
| 54 | +| `make_shared` | `shared_ptr<T>` | `SharedPtr<T>` | |
| 55 | +| `new_ptr` | `*T` | `*mut T` | |
0 commit comments