qobject

Attribute Macro qobject 

Source
#[qobject]
Expand description

Annotate a mod block to make its struct accessible from QML.

The mod block must contain a single struct and it’s impl blocks. The impl blocks are treated as if they had the qobject_impl annotation.

Similar to qobject_impl, this macro implements the following traits:

and a QML module that fits the package name of your Cargo.toml.

This macro has the same parameters as qobject_impl and behaves the same way. In contrast to qobject_impl, this macro tries to identify an existing Drop implementation and will inject detach_qobject when found. If no Drop implementation is found, the macro will generate one. To surpess this injection, you can use the NoDrop option.

§Example

use qtbridge::{QApp, qobject};

#[qobject(Singleton)]
pub mod backend {
    #[derive(Default)]
    pub struct Counter {
       value: i32,
    }

    impl Counter {
        qproperty!("value", Member = value, Notify = "valueChanged");

        #[qsignal]
        fn value_changed(&self);

        #[qslot]
        fn change_value(&mut self, inc: bool) {
            self.value = match inc {
                true => self.value.saturating_add(1),
                false => self.value.saturating_sub(1),
            };
            self.value_changed();
        }
    }
}

const QML_CODE: &str =
r#"
    import QtQuick
    import QtQuick.Controls
    import QtQuick.Layouts
    import qtbridge // must match your cargo package name

    ApplicationWindow {
        visible: true
        title: qsTr("Counter QML app")
        RowLayout {
            anchors.centerIn: parent
            Button {
                text: "-"
                onClicked: Counter.changeValue(false)
            }
            Button {
                text: "+"
                onClicked: Counter.changeValue(true)
            }
        }
    }
"#;

fn main() {
    QApp::new()
        .register::<backend::Counter>()
        .load_qml(QML_CODE.as_bytes())
        .run();
}