简体   繁体   English

QML:如果其名称被组件本地属性遮蔽,如何访问上下文属性?

[英]QML: How to access context property if its name is shadowed by a component-local property?

My code: 我的代码:

main.cpp : main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>

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

    QQmlApplicationEngine engine;

    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    engine.rootContext()->setContextProperty("text", "hey");

    return app.exec();
}

main.qml : main.qml

import QtQuick 2.5
import QtQuick.Window 2.2

Window {
    id: window
    visible: true
    width: 640
    height: 480

    Text {
        text: text
    }
}

Of course, the text: text line doesn't do what I want it to, because of name shadowing. 当然, text: text行不能做我想要的,因为名称阴影。

I worked around that by setting a property on the root object, rather than on the root context, and using text: window.text . 我通过在根对象上设置属性而不是根上下文并使用text: window.text

Is there any real fix though? 有没有真正的解决方案?

You don't. 你没有。 Using text for the name of a context property is like the worst possible choice. 使用text作为上下文属性的名称就像是最糟糕的选择。 You'd literally do better by using blahblah . 你真的会用blahblah做得更好。 Why invite trouble? 为何选择麻烦?

You can implement an alias to access the context property in the root object while also exposing the root object as a dynamic scope property. 您可以实现别名以访问根对象中的上下文属性,同时还将根对象公开为动态范围属性。 This will have the advantage of still being able to use the context property while avoiding the expensive dynamic property lookup all the way down to the root , while still providing an alternative , albeit a less efficient way to get to the context property in the cases where it is shadowed. 这将具有仍然能够使用上下文属性同时避免昂贵的动态属性查找一直到根目录的优点,同时仍然提供替代方案,尽管在如下情况下获取上下文属性的效率较低。它被遮蔽了。

Update: Actually there is logical reason to assume that context properties are any faster to lookup than a regular dynamic scope object property. 更新:实际上有逻辑上的理由假设上下文属性比常规动态范围对象属性更快查找。 In this aspect, the above paragraph can only be used to provide a secondary identifier to access the shadowed property. 在这方面,上面的段落只能用于提供访问被遮蔽属性的辅助标识符。

As mentioned in the comments, a singleton will actually make the most sense in this usage context, as it is directly resolved from an import rather than involving lookups, plus you can import as which can be useful to solve name conflicts. 正如评论中所提到的,单例实际上在这个使用上下文中最有意义,因为它直接从导入而不是涉及查找中解析,而且您可以import as它可以用来解决名称冲突。 If you want to have multiple objects exposed via a singleton, instead of exposing each one as a separate singleton you can just have the different objects members of the singleton, such can be added dynamically as properties, model items or whatever serves the particular need. 如果您希望通过单例显示多个对象,而不是将每个对象公开为单独的单例,您可以只拥有单例的不同对象成员,这些可以作为属性,模型项或任何满足特定需要的内容动态添加。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM