Search code examples
c++qtqmlqtquick2qt-quick

Diiference between setContextProperty and setProperty of object


I really confuse right now

What's is the difference between

QQmlApplicationEngine engine;
engine.rootContext().setContextProperty("myObject",&userData);

and

object->setProperty("myObject", myObject)

Here is the QML file

ApplicationWindow {
id: applicationWindow1

Item {
    id: propertyHolder
    property MyObject myObject
}

I had read how to use QML binding but still hasn't figure it out. Please help Thanks

EDIT : ======================= I attached snippet code here

ApplicationWindow {
id: applicationWindow1

Item {
    id: propertyHolder
    property MyClass myClass
}

Button {
    onClicked : 
        propertyHolder.myClass.doSomething()
}

main.cpp

QQmlApplicationEngine engine;
QQmlContext* context = engine.rootContext();

MyClass myClass;
context->setContextProperty("myClass",&myClass);
engine.load(QUrl("qrc:///mainControl.qml"));

And when i clicked on the button, it gave me a null error for calling method Where did i go wrong?


Solution

  • setProperty is a member of QObject and is used to set a value for a property of a QObject. While setContextProperty is a member of QQmlContext class and is used to set the value of a name property on a qml context. You can read in the Qt documentation about QQmlContext :

    Each QQmlContext contains a set of properties, distinct from its QObject properties, that allow data to be explicitly bound to a context by name. The context properties are defined and updated by calling QQmlContext::setContextProperty().