1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
use crate::{QObject, QPtr, QString};
use cpp_core::{DynamicCast, StaticUpcast};
use std::error::Error;
use std::fmt;
pub struct FindChildError(FindChildErrorInner);
enum FindChildErrorInner {
NotFound {
name: String,
},
TypeMismatch {
name: String,
target_type: &'static str,
},
}
impl fmt::Display for FindChildError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.0 {
FindChildErrorInner::NotFound { name } => write!(f, "child \"{}\" not found", name),
FindChildErrorInner::TypeMismatch { name, target_type } => write!(
f,
"child \"{}\" cannot be converted to type {}",
name, target_type
),
}
}
}
impl fmt::Debug for FindChildError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self)
}
}
impl Error for FindChildError {}
impl QObject {
pub unsafe fn find_child<T>(&self, name: &str) -> Result<QPtr<T>, FindChildError>
where
QObject: DynamicCast<T>,
T: StaticUpcast<QObject>,
{
let ptr = self.find_child_q_object_1a(&QString::from_std_str(name));
if ptr.is_null() {
return Err(FindChildError(FindChildErrorInner::NotFound {
name: name.into(),
}));
}
let ptr = ptr.dynamic_cast();
if ptr.is_null() {
return Err(FindChildError(FindChildErrorInner::TypeMismatch {
name: name.into(),
target_type: std::any::type_name::<T>(),
}));
}
Ok(ptr)
}
}