Description
Hello. One point that I see missing from both the official Qt documentation and this guide is distinguishing C++ model types and C++ visual types. I think most users use the visual types provided by QtQuick or Qt Design Studio instead of creating their own visual components. And they use C++ for model / data backend. So it is important to emphasize what is the most natural integration type for this use case.
Usually data needs to be persistent and not be created / destroyed when you navigate between different views. Furthermore you sometimes need to initialize the object in some specific way. For example pass a handle to a data base or to an IPC (inter-process communication) object to it. This means that the only integration method that works in this situation is using qmlRegisterSingletonInstance
. (I don't think lifetime concerns is a problem since these days everyone is familiar with unique_ptr
, whereas if you need to initialize your object in some way or pass some specific arguments to it, having the QML engine create it is either impossible or very hard with no benefits). In summary, if you really want your model to be independent of your view, you want to also make the lifetime independent.
It seems to me that the guideline should be presented in this way:
- If your C++ type is a model then use
qmlRegisterSingletonInstance
and keep your instance as aunique_ptr
or parent it to the engine. If you want to duplicate your data for each view that uses the model, or if your model does not need to be persistent between views then useqmlRegisterType
- If your C++ type is a custom visual type then use
qmlRegisterType
The reason I think this should be emphasized is that all Qt documentation emphasize the integration methods that create the object from QML. This is not practical for more than 90% of models in my experience due to the above limitations and leads to wasted time trying to fit a square peg in a round hole.