Skip to content

Commit 382d28b

Browse files
Leon Matthesahayzen-kdab
authored andcommitted
Add cxx_qt::Initialize trait.
Useful for avoiding Constructor boilerplate when all you want is to initialize the QObject after construction.
1 parent 0a996d3 commit 382d28b

1 file changed

Lines changed: 42 additions & 0 deletions

File tree

crates/cxx-qt/src/lib.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,3 +193,45 @@ pub trait Constructor<Arguments>: CxxQtType {
193193
// By default, do nothing
194194
}
195195
}
196+
197+
/// This trait can be implemented on any [CxxQtType] to automatically define a default constructor
198+
/// that calls the `initialize` function after constructing a default Rust struct.
199+
///
200+
/// The default constructor will have the following signature:
201+
/// ```ignore
202+
/// cxx_qt::Constructor<()>
203+
/// ```
204+
// TODO: Once the QObject type is available in the cxx-qt crate, also auto-generate a default
205+
// constructor that takes QObject and passes it to the parent.
206+
pub trait Initialize: CxxQtType {
207+
/// This function is called to initialize the QObject after construction.
208+
fn initialize(self: core::pin::Pin<&mut Self>);
209+
}
210+
211+
impl<T> Constructor<()> for T
212+
where
213+
T: Initialize,
214+
T::Rust: Default,
215+
{
216+
type NewArguments = ();
217+
type BaseArguments = ();
218+
type InitializeArguments = ();
219+
220+
fn new(_arguments: ()) -> <Self as CxxQtType>::Rust {
221+
<Self as CxxQtType>::Rust::default()
222+
}
223+
224+
fn route_arguments(
225+
_arguments: (),
226+
) -> (
227+
Self::NewArguments,
228+
Self::BaseArguments,
229+
Self::InitializeArguments,
230+
) {
231+
((), (), ())
232+
}
233+
234+
fn initialize(self: core::pin::Pin<&mut Self>, _arguments: Self::InitializeArguments) {
235+
Self::initialize(self);
236+
}
237+
}

0 commit comments

Comments
 (0)