// Copyright (C) 2017 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
/*!
\page qtqml-cppintegration-interactqmlfromcpp.html
\title Interacting with QML Objects from C++
\brief Description of how to load and access QML objects from C++ code

All QML object types are QObject-derived types, whether they are internally
implemented by the engine or \l
{qtqml-cppintegration-definetypes.html}{defined by third-party
sources}. This means the QML engine can use the Qt \l{Meta Object System} to
dynamically instantiate any QML object type and inspect the created objects.

This is useful for creating QML objects from C++ code, whether to display a QML
object that can be visually rendered, or to integrate non-visual QML object data
into a C++ application. Once a QML object is created, it can be inspected from
C++ in order to read and write to properties, invoke methods and receive signal
notifications.

For more information about C++ and the different QML integration methods,
see the
\l {Overview - QML and C++ Integration} {C++ and QML integration overview} page.

\section1 Loading QML Objects from C++

A QML document can be loaded with QQmlComponent or QQuickView. QQmlComponent
loads a QML document as a C++ object that can then be modified from C++ code.
QQuickView also does this, but as QQuickView is a QWindow-derived class, the
loaded object will also be rendered into a visual display; QQuickView is
generally used to integrate a displayable QML object into an application's
user interface.

For example, suppose there is a \c MyItem.qml file that looks like this:

\snippet qml/qtbinding/loading/MyItem.qml start
\snippet qml/qtbinding/loading/MyItem.qml end

This QML document can be loaded with QQmlComponent or QQuickView with the
following
C++ code. Using a QQmlComponent requires calling QQmlComponent::create() to
create
a new instance of the component, while a QQuickView automatically creates an
instance of the
component, which is accessible via QQuickView::rootObject():

\table
\row
\li
\snippet qml/qtbinding/loading/main.cpp QQmlComponent-a
\dots 0
\snippet qml/qtbinding/loading/main.cpp QQmlComponent-b
\li
\snippet qml/qtbinding/loading/main.cpp QQuickView
\endtable

This \c object is the instance of the \c MyItem.qml component that has been
created. You can now modify the item's properties using
\l QObject::setProperty() or \l QQmlProperty::write():

\snippet qml/qtbinding/loading/main.cpp properties

The difference between \c QObject::setProperty() and \c QQmlProperty::write()
is that the latter will also remove the binding in addition to setting the
property value. For example, suppose the \c width assignment above had been a
binding to \c height:

\code
    width: height
\endcode

If the \c height of the \c Item changed after the
\c {object->setProperty("width", 500)} call, the \c width would be updated
again, as the binding remains active. However, if the \c height changes after the
\c {QQmlProperty(object, "width").write(500)} call, the \c width will not be
changed, as the binding does not exist anymore.

Alternatively, you can cast the object to its actual type and call methods with
compile-time safety. In this case the base object of \c MyItem.qml is an
\l Item, which is defined by the QQuickItem class:

\snippet qml/qtbinding/loading/main.cpp cast

You can also connect to any signals or call methods defined in the component
using QMetaObject::invokeMethod() and QObject::connect(). See \l {Invoking QML Methods}
and \l {Connecting to QML Signals} below for further details.

\section1 Accessing QML Objects via well-defined C++ Interfaces

The best way of interacting with QML from C++ is to define an interface for
doing so in C++ and accessing it in QML itself. With other methods, refactoring
your QML code can easily lead to your QML / C++ interaction breaking. It also
helps to reason about the interaction of QML and C++ code, as having it driven
via QML can be more easily reasoned about by both users and tooling such as
qmllint. Accessing QML from C++ will lead to QML code that cannot be understood
without manually verifying that no outside C++ code is modifying a given QML
component, and even then the extent of the access might change over time, making
continued use of this strategy a maintenance burden.

To let QML drive the interaction, first you need to define a C++ interface:

\code
class CppInterface : public QObject
{
    Q_OBJECT
    QML_ELEMENT
    // ...
};
\endcode

Using a QML-driven approach, this interface can be interacted with in two ways:

\section2 Singletons

One option is to register the interface as a singleton by adding the \l
QML_SINGLETON macro to the interface, exposing it to all components. Following
that, the interface becomes available via a simple import statement:

\code
import my.company.module

Item {
    Component.onCompleted: {
        CppInterface.foo();
    }
}
\endcode

Use this approach if you need your interface in more places than the root component, as
simply passing down an object would require explicitly passing it on to other
components via a property or utilizing the slow and not recommended method of
using \l {Unqualified access}{unqualified access}.

\section2 Initial properties

Another option is to mark the interface as uncreatable via \l QML_UNCREATABLE
and supplying it to the root QML Component by using \l
QQmlComponent::createWithInitialProperties() and a \l {Required
Properties}{required property} on the QML end.

Your root component may look something like this:

\code
import QtQuick

Item {
    required property CppInterface interface
    Component.onCompleted: {
        interface.foo();
    }
}
\endcode

Marking the property as required here protects the component against being
created without the interface property being set.

You can then initialize your component in the same way as outlined in \l
{Loading QML Objects from C++} except using \c {createWithInitialProperties()}:

\code
    component.createWithInitialProperties(QVariantMap{{u"interface"_s, QVariant::fromValue<CppInterface *>(new CppInterface)}});
\endcode

This method is to be preferred if you know that your interface only needs to be
available to the root component. It also allows for connecting to signals and
slots of the interface more easily on the C++ side.

If neither of these methods suit your needs you may want to investigate the usage of
\l {Using C++ Models with Qt Quick Views}{C++ models} instead.

\section1 Accessing Loaded QML Objects by Object Name

QML components are essentially object trees with children that have siblings and
their own children. Child objects of QML components can be located using the
QObject::objectName property with QObject::findChild(). For example, if the root
item in \c MyItem.qml had a child \l Rectangle item:

\snippet qml/qtbinding/loading/MyItem.qml start
\codeline
\snippet qml/qtbinding/loading/MyItem.qml child
\snippet qml/qtbinding/loading/MyItem.qml end

The child could be located like this:

\snippet qml/qtbinding/loading/main.cpp findChild

Note that an object may have multiple children with the same \c objectName.
For example, \l ListView creates multiple instances of its delegate, so if its
delegate is declared with a particular objectName, the \l ListView will have
multiple children with the same \c objectName. In this case,
QObject::findChildren() can be used to find all children with a matching
\c objectName.

\include warning.qdocinc

\section1 Accessing Members of a QML Object Type from C++

\section2 Properties

Any properties declared in a QML object are automatically accessible from C++.
Given a QML item like this:

\snippet qml/qtbinding/properties-qml/MyItem.qml 0

The value of the \c someNumber property can be set and read using QQmlProperty,
or QObject::setProperty() and QObject::property():

\snippet qml/qtbinding/properties-qml/main.cpp 0

You should always use QObject::setProperty(), QQmlProperty or
QMetaProperty::write() to change a QML property value, to ensure the QML
engine is made aware of the property change. For example, say you have a
custom type \c PushButton with a \c buttonText property that internally
reflects the value of a \c m_buttonText member variable. Modifying the member
variable directly like this is not a good idea:

\code
//bad code
QQmlComponent component(engine, "MyButton.qml");
PushButton *button = qobject_cast<PushButton*>(component.create());
button->m_buttonText = "Click me";
\endcode

Since the value is changed directly, this bypasses Qt's \l{The Meta-Object
System}{meta-object system} and the QML engine is not made aware of the
property change. This means property bindings to \c buttonText would not be
updated, and any \c onButtonTextChanged handlers would not be called.

\section2 Invoking QML Methods

All QML methods are exposed to the meta-object system and can be called from
C++ using QMetaObject::invokeMethod(). You can specify types for the parameters
and the return value after the colon character, as shown in the code snippet
below.  This can be useful, for example, when you want to connect a signal in
C++ with a certain signature to a QML-defined method. If you omit the types,
the C++ signature will use QVariant.

Here is a C++ application that calls a QML method using
QMetaObject::invokeMethod():

\table
\row
\li QML
\li \snippet qml/qtbinding/functions-qml/MyItem.qml 0
\row
\li C++
\li \snippet qml/qtbinding/functions-qml/main.cpp 0
\endtable

Notice the parameter and return type specified after the colon. You can use \l
{QML Value Types}{value types} and \l {QML Object Types}{object types} as type
names.

If the type is omitted or specified as \c var in QML, then you must pass
QVariant as type with Q_RETURN_ARG() and Q_ARG() when calling
QMetaObject::invokeMethod.

\section2 Connecting to QML Signals

All QML signals are automatically available to C++, and can be connected to
using QObject::connect() like any ordinary Qt C++ signal. In return, any C++
signal can be received by a QML object using
\l {qtqml-syntax-signals.html}{signal handlers}.

Here is a QML component with a signal named \c qmlSignal that is emitted with
a string-type parameter. This signal is connected to a C++ object's slot using
QObject::connect(), so that the \c cppSlot() method is called whenever the
\c qmlSignal is emitted:

\table
\row
\li
\snippet qml/qtbinding/signals-qml/MyItem.qml 0
\row
\li
\snippet qml/qtbinding/signals-qml/myclass.h 0
\codeline
\snippet qml/qtbinding/signals-qml/main.cpp 0
\endtable

A QML object type in a signal parameter is translated to a pointer to the class
in C++:

\table
\row
\li

\qml
 // MyItem.qml
 import QtQuick 2.0

 Item {
     id: item
     width: 100; height: 100

     signal qmlSignal(anObject: Item)

     MouseArea {
         anchors.fill: parent
         onClicked: item.qmlSignal(item)
     }
 }
\endqml

\li
\code
 class MyClass : public QObject
 {
     Q_OBJECT
 public slots:
     void cppSlot(QQuickItem *item) {
        qDebug() << "Called the C++ slot with item:" << item;

        qDebug() << "Item dimensions:" << item->width()
                 << item->height();
     }
 };

 int main(int argc, char *argv[]) {
     QGuiApplication app(argc, argv);

     QQuickView view(QUrl::fromLocalFile("MyItem.qml"));
     QObject *item = view.rootObject();

     MyClass myClass;
     QObject::connect(item, SIGNAL(qmlSignal(QVariant)),
                      &myClass, SLOT(cppSlot(QVariant)));

     view.show();
     return app.exec();
 }
\endcode
\endtable

*/
