@peter-thompson said in What is the best practice for passing C++ data objects to QML that is contained in a QQuickWidget?:
@jeremy_k said in What is the best practice for passing C++ data objects to QML that is contained in a QQuickWidget?:
I had not noticed a warning against setting properties in root objects. That's the method I prefer, as it resembles what I would generally do if instantiating the component as a node of a larger QML tree. Properties of the root component can serve as documentation of inputs. Multiple property initialization functions such as QQmlComponent::setInitialProperties() might be more efficient.
The warning I was referring to is mentioned in two places: Overview - QML and C++ Integration and Interacting with QML Objects from C++. It says:
Warning: Although it is possible to access QML objects from C++ and manipulate them, it is not the recommended approach, except for testing and prototyping purposes. One of the strengths of QML and C++ integration is the ability to implement UIs in QML separate from the C++ logic and dataset backend, and this fails if the C++ side starts manipulating QML directly. Such an approach also makes changing the QML UI difficult without affecting its C++ counterpart.
I think it may be specifically referring to navigating the QML object tree and setting properties/invoking methods on child objects. So it might not apply to working with the root object alone.
That's my reading, and hence the subsequent surprise. I generally attempt to treat children of widget instances similarly.
If there are a significant number of QQuickWidgets, consider instantiating an independent QQmlEngine, rather than relying on each widget to create its own.
This is an interesting idea that I had not considered. How would this work? Would I still use QQuickWidgets to integrate the QML with the widgets visually/structurally, and just pass the already-created QQmlEngine instance that they should use?
Exactly. The engine comes with a component cache, network access manager, and some additional configurable features that can be more efficient to reuse.