Skip to main content

qtbridge/
lib.rs

1// Copyright (C) 2025 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only
3
4#![doc = include_str!("../README.md")]
5// The README shows a complete main.rs on purpose.
6#![allow(clippy::needless_doctest_main)]
7
8#[doc(hidden)]
9pub use qtbridge_runtime;
10pub use qtbridge_runtime::QModelItem;
11pub use qtbridge_runtime::QVariantConvertible;
12pub use qtbridge_runtime::QMetaTypeCompatible;
13pub use qtbridge_runtime::QPropertyMember;
14pub use qtbridge_runtime::registry::collect_garbage;
15#[doc(hidden)]
16pub use qtbridge_interfaces;
17#[doc(hidden)]
18pub use qtbridge_type_lib;
19
20pub mod special_traits {
21      //! Traits that enable Rust types to fulfill specific QML roles.
22      //!
23      //! Implement one of these on your struct and pass it as `Base = ...`
24      //! to [`qobject`](crate::qobject).
25      //!
26      //! Note that only one of these traits can be implemented for the same
27      //! type.
28      //!
29      //! - [`QListModel`](crate::QListModel) exposes a list to QML ListView / Repeater
30      //! - [`QTableModel`](crate::QTableModel) exposes a table to QML TableView
31      //! - [`QParserStatus`](crate::QParserStatus) receives notifications during component construction
32}
33
34/// Annotate an `impl` or `mod` block to make its struct accessible from QML.
35///
36/// The macro implements a range of traits that enable bridging from Rust
37/// to QML. The mechanism is based on the implementation of various traits with
38/// some code generated at macro expansion time. You should not implement these
39/// traits yourself. As a user, you should only interact with:
40///
41/// * [`QmlObject`]
42/// * [`QmlElement`] (only non-generic types)
43///
44/// This macro makes it possible to declare the following items within the
45/// `impl` block:
46///
47/// * signals with the [`qsignal`] attribute macro
48/// * invokable functions with the [`qslot`] attribute macro
49/// * struct properties with the [`qproperty`] macro
50///
51/// Further, it allows the struct to implement traits to fulfill specific QML purposes.
52/// These are called `Base` traits. The available base traits are:
53///
54/// * [`QParserStatus`] to receive notifications during QML component construction.
55/// * [`QListModel`] to make a `struct` accessible by QML ListView, QML Repeater, or similar.
56/// * [`QTableModel`] to make a `struct` accessible by QML TableView.
57///
58/// Only one of those traits can be implemented at the same time.
59///
60/// # Usage
61///
62/// The [`qobject`] macro can be applied to a `impl` block of the
63/// target `struct`. Only a single `impl` block can be annotated with this macro and
64/// all applications of [`qsignal`], [`qslot`] and [`qproperty`] have to be limited to
65/// this block.
66///
67/// Alternatively, it may be applied to the `mod` block that contains the `struct`
68/// definition and its associated `impl` blocks.
69///
70/// In order to communicate with QML, the macro creates bridging objects that are attached
71/// to the respective structs. Therefore, objects created with [`qobject`] should be
72/// created with [`default_with_attached_qobject`](QmlObject::default_with_attached_qobject)
73/// or expanded with [`attach_qobject`](QmlObject::attach_qobject). This is not necessary if
74/// the struct is instantiated in QML.
75///
76/// When [`register`](QmlElement::register) is called, the macro creates a QML
77/// module whose name matches your Cargo package name. So for a `Cargo.toml` with
78/// ```toml
79/// [package]
80/// name = "hello_world"
81///
82/// [dependencies]
83/// qtbridge
84/// ```
85/// the QML file has to contain
86///
87/// ```qml
88/// import hello_world
89/// ```
90///
91/// ## Requirements
92///
93/// A `struct` using [`qobject`] must implement the [`Default`] trait when it
94/// is registered as a QML element; `NoQmlElement` types need no `Default`.
95/// The static function [`register`](QmlElement::register) has to be called at the start of the
96/// main function to make this `struct` instantiable from QML.
97///
98/// ## Parameters
99///
100/// Parameters to adjust the macro behavior are passed as comma-separated keywords or keyword-value pairs.
101///
102/// **Base = BaseTrait**
103///
104/// Set the base trait. Must be one of the [`special_traits`] and must be
105/// implemented for the corresponding `struct`. Only one base trait can be set
106/// per type.
107///
108/// **ConvertToCamelCase**
109///
110/// Rust uses snake_case for function names, while in QML camelCase is more common. Use this option
111/// to convert function names to camelCase when exposed to QML.
112///
113/// **NoQmlElement**
114///
115/// Do not implement [`QmlElement`]. [`QmlElement`] registers the `struct` in the QML type system,
116/// allowing you to instantiate this type in QML. The `NoQmlElement` option can be useful to turn off
117/// instantiatability within QML or to provide a manual implementation of this trait with better control
118/// over naming and versioning.
119///
120/// **Singleton**
121///
122/// Implement [`QmlElement`] as a [singleton](https://doc.qt.io/qt-6/qml-singleton.html). A singleton
123/// is accessed from QML as a single shared instance of the type, using the type name as identifier.
124/// This is useful for application-wide data, global settings, or service objects.
125///
126/// ## Automatic registration
127///
128/// When the `linkme` cargo feature is enabled, [`register`](QmlElement::register) is called at
129/// application start for every annotated type without any additional code. The crate
130/// [`Linkme`](https://crates.io/crates/linkme) is used for this purpose:
131///
132/// ```toml
133/// qtbridge = { version = "0.2", features = ["linkme"] }
134/// ```
135///
136/// The feature applies to every type annotated with [`qobject`] in the whole application,
137/// including its dependencies. Types annotated with `NoQmlElement` are exempt, as they do
138/// not implement [`QmlElement`].
139///
140/// ## Example
141///
142/// ```rust
143/// use qtbridge::{QApp, qobject};
144///
145/// #[derive(Default)]
146/// pub struct Counter {
147///    value: i32,
148/// }
149///
150/// #[qobject(Singleton)]
151/// impl Counter {
152///     qproperty!("value", Member = value, Notify = value_changed);
153///
154///     #[qsignal]
155///     fn value_changed(&mut self);
156///
157///     #[qslot]
158///     fn change_value(&mut self, inc: bool) {
159///         self.value = match inc {
160///             true => self.value.saturating_add(1),
161///             false => self.value.saturating_sub(1),
162///         };
163///         self.value_changed();
164///     }
165/// }
166///
167/// const QML_CODE: &str =
168/// r#"
169///     import QtQuick
170///     import QtQuick.Controls
171///     import QtQuick.Layouts
172///     import qtbridge // must match your cargo package name
173///
174///     ApplicationWindow {
175///         visible: true
176///         title: qsTr("Counter QML app")
177/// #       Component.onCompleted: closeTimer.start()
178/// #       Timer {
179/// #           id: closeTimer
180/// #           interval: 1
181/// #           onTriggered: Qt.quit()
182/// #       }
183///         RowLayout {
184///             anchors.centerIn: parent
185///             Button {
186///                 text: "-"
187///                 onClicked: Counter.changeValue(false)
188///             }
189///             Button {
190///                 text: "+"
191///                 onClicked: Counter.changeValue(true)
192///             }
193///         }
194///     }
195/// "#;
196///
197/// fn main() {
198///     QApp::new()
199///         .register::<Counter>()
200///         .load_qml(QML_CODE.as_bytes())
201///         .run();
202/// }
203/// ```
204///
205#[doc(inline)]
206pub use qtbridge_gen::qobject;
207
208
209/// Annotates a function as a signal that can be handled in QML.
210///
211/// Signals can be called from Rust and the signal handler can be defined in QML. This is the
212/// recommended way to invoke QML code from Rust.
213///
214/// ### Requirements
215///
216/// - The signal must be defined within a `mod` or `impl` block, annotated with [`qobject`].
217/// - The first argument of the annotated function must be `&mut self`.
218/// - All other parameter types and the return type must implement [`QMetaTypeCompatible`].
219/// - The function must not have a body (end with a semicolon or empty curly braces `{}`).
220///
221/// ```rust
222/// # use qtbridge::qobject;
223/// # #[derive(Default)]
224/// # pub struct Backend {
225/// # }
226/// #
227/// #[qobject]
228/// impl Backend {
229///     #[qsignal]
230///     fn value_changed(&mut self, new_value: i32);
231///     #[qsignal]
232///     fn event_triggered(&mut self){}
233/// }
234/// ```
235///
236/// To receive a notification on the QML side, the object definition has to declare a signal handler named
237/// `on<Signal>`, where `<Signal>` is the name of the signal, with the first letter capitalized. Note that
238/// the rest of the function name is not affected and the signal handler for e.g. `value_changed` will be
239/// `onValue_changed`.
240///
241/// ```qml,ignore
242/// Backend {
243///     onValue_changed: console.log("Value changed");
244/// }
245/// ```
246/// Alternatively you can instantiate a `Connection` object with the respective signal handler.
247/// ```qml,ignore
248/// Connection {
249///     target: backend
250///     function onValue_changed() {
251///         console.log("Value changed");
252///     }
253/// }
254/// ```
255///
256/// For more details see <https://doc.qt.io/qt-6/qtqml-syntax-signals.html>
257///
258/// ### Parameters
259///
260/// ***qml_name***
261///
262/// The signal name as seen in QML. Defaults to the Rust function name.
263///
264#[doc(inline)]
265#[rust_analyzer::completions(ignore_flyimport)]
266pub use qtbridge_gen::qsignal;
267
268/// Annotates a function as invokable from QML.
269///
270/// Such a function is also registered as a Qt slot, so it can be the target of a
271/// [signal-slot connection](https://doc.qt.io/qt-6/signalsandslots.html).
272///
273/// ### Requirements
274///
275/// - Has to be defined within a `mod` or `impl` block, annotated with [`qobject`].
276/// - The annotated function must have a body.
277/// - The first argument of the annotated function must be `&self` or `&mut self`.
278/// - All other parameter types and the return type must implement [`QMetaTypeCompatible`].
279///
280/// ### Example
281/// ```rust
282/// # use qtbridge::qobject;
283/// # #[derive(Default)]
284/// # pub struct Backend {
285/// #     value: i32,
286/// # }
287/// #
288/// # #[qobject]
289/// # impl Backend {
290/// #[qslot]
291/// fn set_value(&mut self, new_value: i32) {
292///     self.value = new_value;
293/// }
294/// # }
295/// ```
296///
297/// ### Parameters
298///
299/// **qml_name**
300///
301/// The function name as seen from QML. Defaults to the Rust function name.
302#[doc(inline)]
303#[rust_analyzer::completions(ignore_flyimport)]
304pub use qtbridge_gen::qslot;
305
306// TODO: Remove name mangling from doc snippets.
307/// Registers a property to be accessible from QML.
308///
309/// ### Requirements
310///
311/// - The property must be defined within a `mod` or `impl` block, annotated with [`qobject`].
312/// - The first parameter is the property name. It must begin with a lower case letter and
313///   can only contain letters, numbers and underscores.
314/// - The property type must implement [`QPropertyMember`].
315/// - The return value of the getter (specified via `Read` parameter) must match the property type.
316/// - The value parameter of the setter (specified via `Write` parameter) must match the property type.
317/// - The member of the `struct` (specified via `Member` parameter) must match the property type.
318/// - A signal indicating any property changes (specified via `Notify` parameter) must be
319///   emitted explicitly by any code that changes the property. The framework does not emit
320///   it automatically.
321/// - Getter and setter methods must be defined within the same `impl` block in which the property
322///   is declared.
323///
324/// A property may be **accessor-based** or **member-based** or a mix of both (see the
325/// [syntax](#qproperty-syntax) section for details).
326///
327/// ### Accessor based property
328///
329/// A pure accessor-based property can be declared together with a range of functions:
330/// ```rust
331/// # use qtbridge::qobject;
332/// # #[derive(Default)]
333/// # pub struct Backend {
334/// #     value: i32,
335/// # }
336/// #
337/// # #[qobject]
338/// # impl Backend {
339/// qproperty!("myProperty", Read = get_value, Write = set_value, Notify = my_property_changed);
340///
341/// pub fn get_value(&self) -> i32 { self.value }
342/// pub fn set_value(&mut self, value: i32) {
343///     self.value = value;
344///     self.my_property_changed();
345/// }
346/// #[qsignal]
347/// pub fn my_property_changed(&mut self);
348/// # }
349/// ```
350/// The getter method that returns the current value of the property, the setter (if provided) must
351/// take the input value of the property as its first argument (after `&mut self`).
352///
353/// ### Member based property
354///
355/// Member based properties do not require a setter or getter and QML will directly read and write
356/// to the member. A `Notify` signal must be provided. Qt emits it automatically when QML writes
357/// the property, but when Rust code changes the member directly the notify signal must be emitted
358/// explicitly.
359///
360/// A `struct` containing a member-based property may look like:
361/// ```rust
362/// # use qtbridge::qobject;
363/// #[derive(Default)]
364/// struct Text {
365///     msg: String
366/// }
367///
368/// #[qobject]
369/// impl Text {
370///     qproperty!("message", Member = msg, Notify = message_changed);
371///
372///     #[qsignal]
373///     fn message_changed(&mut self);
374/// }
375/// ```
376///
377/// More information about Qt properties: <https://doc.qt.io/qt-6/properties.html>.
378///
379/// ### Parameters of `qproperty!`
380///
381/// **Name**
382///
383/// The first argument is a string literal specifying the name of the Qt property.
384/// This is the name under which the property is exposed to QML and should follow the
385/// naming rules from [requirements](#requirements-2).
386///
387/// **Read**
388///
389/// Specifies the getter method for the property in the format `Read = getter_name`.
390///
391/// **Write**
392///
393/// Specifies the setter method for the property in the format `Write = setter_name`.
394///
395/// **Member**
396///
397/// Specifies the struct member variable that will be accessed if no getter or setter
398/// are provided. Expected format: `Member = var_name`.
399///
400/// **Notify**
401///
402/// Specifies the name of the signal that has to be emitted when the property changes.
403/// Expected format: `Notify = signal_name`.
404///
405/// **Constant**
406///
407/// A constant property is not allowed to have `Write` or `Notify` parameters. If no
408/// `Notify` is provided in combination with member, `Constant` is required.
409/// Expected as a single keyword without an assignment expression.
410///
411/// **Default**
412///
413/// Marks this as the QML default property. Content placed inside an object literal
414/// without an explicit property assignment is written to it.
415/// Expected as a single keyword without an assignment expression.
416///
417#[doc(inline)]
418pub use qtbridge_gen::qproperty;
419
420pub use qtbridge_runtime::QApp;
421pub use qtbridge_runtime::qresource;
422pub use qtbridge_runtime::QThreadHandle;
423
424#[doc(hidden)]
425pub use qtbridge_runtime::QObjectHolder;
426
427/// Basic functionality for `#[qobject]` types.
428///
429/// This trait connects structs to QML and manages their lifetime under
430/// QML usage. This trait is available on every `#[qobject]` type.
431/// Do not implement this trait manually.
432///
433/// # Object lifetime and ownership
434///
435/// A `#[qobject]` value is a plain Rust value that you can interact normally
436/// with. In order to allow the QML engine to interact with it, it needs to be
437/// wrapped in an `Rc<RefCell<_>>`. QtBridge clones this shared reference,
438/// keeps it alive while in use by QML and borrows references to call into
439/// Rust code.
440///
441/// QtBridge requires all `#[qobject]` types to have a proxy `QObject` on
442/// the QML side. It is attached lazily on its first exposure, or eagerly
443/// with [`QmlObject::default_with_attached_qobject`] and
444/// [`QmlObject::attach_qobject`].
445///
446/// The `QObject` proxy has to follow the Qt lifetime concept: Parents and
447/// Components delete their children in their destructor.
448///
449/// An object whose `QObject` was deleted remains a fully usable Rust value.
450/// The interactions with Qt (emitting signals, updating model views) become
451/// a no-op. On its next exposure to QML a fresh `QObject` is attached.
452/// Connections, bindings and QML references to the old `QObject` are not
453/// restored.
454///
455/// An object no longer referenced from Rust or reachable from QML is freed
456/// by [`collect_garbage`], which runs automatically after each QML
457/// garbage collection and during allocation pressure.
458#[doc(inline)]
459pub use qtbridge_runtime::QmlObject;
460
461/// QmlElement enables QML to instantiate types of this trait.
462///
463/// The trait is usually implemented by [`qobject`]. If you
464/// want to implement this trait manually, you have to add the `NoQmlElement`
465/// option.
466///
467/// [`QmlElement`] defines the [`ELEMENT_NAME`](QmlElement::ELEMENT_NAME)
468/// with which the `struct` can be instantiated in QML and the module name,
469/// [`URI`](QmlElement::URI), which has to be used as import in QML to
470/// use this `struct`.
471///
472/// [`QmlElement`] knows two ways of registering a type. The ordinary way
473/// is to register as an element that can be instantiated in QML:
474///
475/// ```rust
476/// # use qtbridge::qobject;
477/// # #[derive(Default)]
478/// # pub struct Backend {
479/// # }
480/// #
481/// #[qobject(NoQmlElement)]
482/// impl Backend {
483///     #[qslot]
484///     fn say_hello(&self) {
485///         println!("Hello World!")
486///     }
487/// }
488/// impl qtbridge::qtbridge_runtime::QmlElement for Backend {
489///     const URI: &str = "rust_backend";
490///     const ELEMENT_NAME: &str = "Backend";
491///     const MINOR_VERSION: u8 = 0u8;
492///     const MAJOR_VERSION: u8 = 1u8;
493///     const IS_SINGLETON: bool = false;
494/// }
495/// ```
496///
497/// ```qml
498/// import rust_backend
499/// Backend {
500///     id: backend
501/// }
502/// Button {
503///     anchors.centerIn: parent
504///     text: "Hello World!"
505///     onClicked: backend.sayHello()
506/// }
507/// ```
508///
509/// Alternatively, by setting [`IS_SINGLETON`](QmlElement::IS_SINGLETON)
510/// to true, the type is registered as a singleton. That means that only
511/// one instance can be created. It can be accessed with the
512/// [`ELEMENT_NAME`](QmlElement::ELEMENT_NAME):
513///
514/// ```rust
515/// # use qtbridge::qobject;
516/// # #[derive(Default)]
517/// # pub struct Backend {
518/// # }
519/// #
520/// #[qobject(NoQmlElement)]
521/// impl Backend {
522///     #[qslot]
523///     fn say_hello(&self) {
524///         println!("Hello World!")
525///     }
526/// }
527/// impl qtbridge::qtbridge_runtime::QmlElement for Backend {
528///     const URI: &str = "rust_backend";
529///     const ELEMENT_NAME: &str = "Backend";
530///     const MINOR_VERSION: u8 = 0u8;
531///     const MAJOR_VERSION: u8 = 1u8;
532///     const IS_SINGLETON: bool = true;
533/// }
534/// ```
535///
536/// ```qml
537/// import rust_backend
538/// Button {
539///     anchors.centerIn: parent
540///     text: "Hello World!"
541///     onClicked: Backend.sayHello()
542/// }
543/// ```
544///
545/// Further, [`MAJOR_VERSION`](QmlElement::MAJOR_VERSION) and
546/// [`MINOR_VERSION`](QmlElement::MINOR_VERSION) define the version of the
547/// QML module. These fields are mandatory but QML can load a module without
548/// specifying the version
549///
550#[doc(inline)]
551pub use qtbridge_runtime::QmlElement;
552
553pub use qtbridge_gen::QModelItem;
554
555pub use qtbridge_gen::include_bytes_qml;
556
557pub use qtbridge_interfaces::QParserStatus;
558pub use qtbridge_interfaces::{QListModel, QListModelBase};
559pub use qtbridge_interfaces::{QTableModel, QTableModelBase};
560
561#[doc(hidden)]
562pub use qtbridge_interfaces::{QAbstractItemModel, QAbstractItemModelBase};