pub trait Threading: Sized {
// Required method
fn qt_thread(&self) -> CxxQtThread<Self>;
}
Expand description
This trait indicates that the object implements threading and has a method which returns a CxxQtThread.
The QObjects generated by CXX-Qt are neither Send
nor Sync
.
Therefore they may not be passed between threads nor accessed from multiple threads.
To achieve safe multi-threading on the Rust side we use an CxxQtThread. A CxxQtThread represents a reference to the Qt thread that the QObject lives in. When a new Rust thread is started (e.g. in an invokable) the CxxQtThread can be moved into the thread to later update the QObject in a thread safe manner.
§Example
#[cxx_qt::bridge]
mod qobject {
extern "RustQt" {
#[qobject]
type MyStruct = super::MyStructRust;
#[qinvokable]
fn say_hello(self: Pin<&mut MyStruct>);
}
impl cxx_qt::Threading for MyStruct {}
}
use cxx_qt::Threading;
#[derive(Default)]
pub struct MyStructRust;
impl qobject::MyStruct {
pub fn say_hello(self: core::pin::Pin<&mut Self>) {
let qt_thread = self.qt_thread();
// Start a background thread that doesn't block the invokable
std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_secs(1));
// Say hello on the Qt event loop
qt_thread.queue(|_| {
println!("Hello");
}).unwrap();
});
}
}
Required Methods§
Sourcefn qt_thread(&self) -> CxxQtThread<Self>
fn qt_thread(&self) -> CxxQtThread<Self>
Create an instance of a CxxQtThread
This allows for queueing closures onto the Qt event loop from a background thread.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.