IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)

Interacting with QML Objects from C++

Description of how to load and access QML objects from C++ code.

Article lu   fois.

L'auteur

Liens sociaux

Viadeo Twitter Facebook Share on Google+   

Interacting with QML Objects from C++▲

All QML object types are QObject-derived types, whether they are internally implemented by the engine or https://. This means the QML engine can use the Qt https:// 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.

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 MyItem.qml file that looks like this:

 
Sélectionnez
import QtQuick 2.0

Item {
    width: 100; height: 100
}

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():

 
Sélectionnez
// Using QQmlComponent
QQmlEngine engine;
QQmlComponent component(&engine,
        QUrl::fromLocalFile("MyItem.qml"));
QObject *object = component.create();
...
delete object;
 
Sélectionnez
// Using QQuickView
QQuickView view;
view.setSource(QUrl::fromLocalFile("MyItem.qml"));
view.show();
QObject *object = view.rootObject();

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

 
Sélectionnez
object->setProperty("width", 500);
QQmlProperty(object, "width").write(500);

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

 
Sélectionnez
width: height

If the height of the Item changed after the object->setProperty("width", 500) call, the width would be updated again, as the binding remains active. However, if the height changes after the QQmlProperty(object, "width").write(500) call, the 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 MyItem.qml is an https://, which is defined by the QQuickItem class:

 
Sélectionnez
QQuickItem *item = qobject_cast<QQuickItem*>(object);
item->setWidth(500);

You can also connect to any signals or call methods defined in the component using https://() and QObject::connect(). See https:// and https:// below for further details.

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 MyItem.qml had a child https:// item:

 
Sélectionnez
import QtQuick 2.0

Item {
    width: 100; height: 100

    Rectangle {
        anchors.fill: parent
        objectName: "rect"
    }
}

The child could be located like this:

 
Sélectionnez
QObject *rect = object->findChild<QObject*>("rect");
if (rect)
    rect->setProperty("color", "red");

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

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.

Accessing Members of a QML Object Type from C++▲

 

Properties▲

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

 
Sélectionnez
// MyItem.qml
import QtQuick 2.0

Item {
    property int someNumber: 100
}

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

 
Sélectionnez
QQmlEngine engine;
QQmlComponent component(&engine, "MyItem.qml");
QObject *object = component.create();

qDebug() << "Property value:" << QQmlProperty::read(object, "someNumber").toInt();
QQmlProperty::write(object, "someNumber", 5000);

qDebug() << "Property value:" << object->property("someNumber").toInt();
object->setProperty("someNumber", 100);

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 PushButton with a buttonText property that internally reflects the value of a m_buttonText member variable. Modifying the member variable directly like this is not a good idea:

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

Since the value is changed directly, this bypasses Qt's https:// and the QML engine is not made aware of the property change. This means property bindings to buttonText would not be updated, and any onButtonTextChanged handlers would not be called.

Invoking QML Methods▲

All QML methods are exposed to the meta-object system and can be called from C++ using https://(). Method parameters and return values passed from QML are always translated into QVariant values in C++.

Here is a C++ application that calls a QML method using https://():

QML

 
Sélectionnez
// MyItem.qml
import QtQuick 2.0

Item {
    function myQmlFunction(msg) {
        console.log("Got message:", msg)
        return "some return value"
    }
}

C++

 
Sélectionnez
// main.cpp
QQmlEngine engine;
QQmlComponent component(&engine, "MyItem.qml");
QObject *object = component.create();

QVariant returnedValue;
QVariant msg = "Hello from C++";
QMetaObject::invokeMethod(object, "myQmlFunction",
        Q_RETURN_ARG(QVariant, returnedValue),
        Q_ARG(QVariant, msg));

qDebug() << "QML function returned:" << returnedValue.toString();
delete object;

Notice the https://() and https://() arguments for https://() must be specified as QVariant types, as this is the generic data type used for QML method parameters and return values.

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 https://.

Here is a QML component with a signal named 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 cppSlot() method is called whenever the qmlSignal is emitted:

 
Sélectionnez
// MyItem.qml
import QtQuick 2.0

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

    signal qmlSignal(string msg)

    MouseArea {
        anchors.fill: parent
        onClicked: item.qmlSignal("Hello from QML")
    }
}
 
Sélectionnez
class MyClass : public QObject
{
    Q_OBJECT
public slots:
    void cppSlot(const QString &msg) {
        qDebug() << "Called the C++ slot with message:" << msg;
    }
};

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(QString)),
                     &myClass, SLOT(cppSlot(QString)));

    view.show();
    return app.exec();
}

When a QML object type is used as a signal parameter, the parameter should use https:// as the type, and the value should be received in C++ using the QVariant type:

 
Sélectionnez
// MyItem.qml
import QtQuick 2.0

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

    signal qmlSignal(var anObject)

    MouseArea {
        anchors.fill: parent
        onClicked: item.qmlSignal(item)
    }
}
 
Sélectionnez
class MyClass : public QObject
{
    Q_OBJECT
public slots:
    void cppSlot(const QVariant &v) {
       qDebug() << "Called the C++ slot with value:" << v;

       QQuickItem *item =
           qobject_cast<QQuickItem*>(v.value<QObject*>());
       qDebug() << "Item dimensions:" << item->width()
                << item->height();
    }
};

int main(int argc, char *argv[]) {
    QApplication 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();
}

Vous avez aimé ce tutoriel ? Alors partagez-le en cliquant sur les boutons suivants : Viadeo Twitter Facebook Share on Google+   

Ce document est disponible sous la licence https:// telle que publiée par la Free Software Foundation.