Skip to content

Commit c7a92c5

Browse files
authored
Automatically implement Upcast<Self> for all types (#1247)
* cxx-qt: automatically implement Upcast<Self> for all types * cxx-qt: explicit upcasting
1 parent 5d3b2de commit c7a92c5

File tree

3 files changed

+30
-4
lines changed

3 files changed

+30
-4
lines changed

crates/cxx-qt/src/lib.rs

+22
Original file line numberDiff line numberDiff line change
@@ -267,6 +267,28 @@ pub trait Upcast<T> {
267267
}
268268
}
269269

270+
impl<T> Upcast<T> for T {
271+
unsafe fn upcast_ptr(this: *const Self) -> *const Self {
272+
this
273+
}
274+
275+
unsafe fn from_base_ptr(base: *const T) -> *const Self {
276+
base
277+
}
278+
279+
fn upcast(&self) -> &Self {
280+
self
281+
}
282+
283+
fn upcast_mut(&mut self) -> &mut Self {
284+
self
285+
}
286+
287+
fn upcast_pin(self: Pin<&mut Self>) -> Pin<&mut Self> {
288+
self
289+
}
290+
}
291+
270292
/// This trait is automatically implemented by CXX-Qt and you most likely do not need to manually implement it.
271293
/// Trait for downcasting to a subclass, provided the subclass implements [Upcast] to this type.
272294
/// Returns `None` in cases where `Sub` isn't a child class of `Self`.

examples/cargo_without_cmake/src/main.rs

+4-2
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,10 @@
1414
// ANCHOR: book_cargo_imports
1515
pub mod cxxqt_object;
1616

17+
use std::pin::Pin;
18+
1719
use cxx_qt::Upcast;
18-
use cxx_qt_lib::{QGuiApplication, QQmlApplicationEngine, QUrl};
20+
use cxx_qt_lib::{QGuiApplication, QQmlApplicationEngine, QQmlEngine, QUrl};
1921
// ANCHOR_END: book_cargo_imports
2022

2123
// ANCHOR: book_cargo_rust_main
@@ -30,9 +32,9 @@ fn main() {
3032
}
3133

3234
if let Some(engine) = engine.as_mut() {
35+
let engine: Pin<&mut QQmlEngine> = engine.upcast_pin();
3336
// Listen to a signal from the QML Engine
3437
engine
35-
.upcast_pin()
3638
.on_quit(|_| {
3739
println!("QML Quit!");
3840
})

examples/qml_multi_crates/rust/main/src/main.rs

+4-2
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,10 @@
55

66
extern crate qml_multi_crates;
77

8+
use std::pin::Pin;
9+
810
use cxx_qt::Upcast;
9-
use cxx_qt_lib::{QGuiApplication, QQmlApplicationEngine, QUrl};
11+
use cxx_qt_lib::{QGuiApplication, QQmlApplicationEngine, QQmlEngine, QUrl};
1012

1113
fn main() {
1214
cxx_qt::init_crate!(qml_multi_crates);
@@ -21,9 +23,9 @@ fn main() {
2123
}
2224

2325
if let Some(engine) = engine.as_mut() {
26+
let engine: Pin<&mut QQmlEngine> = engine.upcast_pin();
2427
// Listen to a signal from the QML Engine
2528
engine
26-
.upcast_pin()
2729
.on_quit(|_| {
2830
println!("QML Quit!");
2931
})

0 commit comments

Comments
 (0)