Diiference between setContextProperty and setProperty of object

风格不统一 提交于 2020-08-05 06:43:07

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/28924622/diiference-between-setcontextproperty-and-setproperty-of-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!