The generated QObject

One of the key features of CXX-Qt is the ability to create your own QObjects from Rust. This is what the #[qobject] macro is for. This page serves to document the details of what is generated and how to interact with the generated QObject from Rust.

The #[qobject] macro generates a QObject for a type alias to a Rust struct. Whilst this QObject is a C++ type, CXX-Qt will automatically wrap it as a CXX Opaque Type.

If the bridge module is named qobject, then the C++ type can be reached via qobject::T

Anatomy

Any QObject generated by CXX-Qt is just a C++ QObject subclass that owns an instance of the Rust struct.

By default, the instance of the Rust struct is constructed using the Default trait. If the Rust struct cannot implement Default, providing a custom constructor with the Constructor trait is required.

The C++ object will defer any state to the Rust struct, and is therefore only a thin wrapper.

📝 Note: The inner Rust struct of the QObject is owned by that QObject. So when the C++ object is destructed the inner Rust struct will be dropped as well.

See extern "RustQt" for details on implementing properties, invokables, and signals.

See nested objects for referencing another QObject.

C++ context

When implementing methods in the C++ context (e.g. for invokables) these need to be implemented on the type defined in the bridge.

For example, if the bridge module was called qobject and the type was called T, an impl block would be written as impl qobject::T { ... }.

Methods from traits, such as Threading, are available in the C++ context

From a C++ context the Rust context can be reach by using methods on the CxxQtType trait

Rust context

The only requirement for the Rust struct is that it has a Default or that the QObject implements cxx_qt::Constructor.

Otherwise, the Rust struct can be used in the same way as any normal Rust struct.