对象的 setContextProperty 和 setProperty 的区别 [英] Diiference between setContextProperty and setProperty of object

查看:189
本文介绍了对象的 setContextProperty 和 setProperty 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在真的很困惑

两者有什么区别

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

object->setProperty("myObject", myObject)

这是QML文件

ApplicationWindow {
id: applicationWindow1

Item {
    id: propertyHolder
    property MyObject myObject
}

我已经阅读了如何使用 QML 绑定,但仍然没有弄清楚.请帮忙谢谢

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?

推荐答案

setPropertyQObject 的成员,用于为 QObject 的属性设置值代码>QObject.setContextPropertyQQmlContext 类的成员,用于在 qml 上下文中设置 name 属性的值.您可以在 Qt 文档中阅读有关 QQmlContext 的内容:

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 :

每个 QQmlContext 包含一组属性,不同于它的QObject 属性,允许将数据显式绑定到按名称上下文.上下文属性由调用 QQmlContext::setContextProperty().

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

这篇关于对象的 setContextProperty 和 setProperty 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆