【问题标题】:How to assign a context-variable to a property with the same name in QML?如何将上下文变量分配给 QML 中具有相同名称的属性?
【发布时间】:2017-02-07 00:12:04
【问题描述】:

这是以下代码的结果:

main.qml

import QtQuick 2.8 

Item {
    Reusable {
        index: 1234      // reusable with a custom index
    }   

    ListView {
        anchors { fill: parent; margins: 20; topMargin: 50 }
        model: 3

        // Reusable with an index given by the ListView
        delegate: Reusable {
            index: index // <- does not work, both 'index' point to 
                         //    the index property
        }   
    }   
}

Reusable.qml

import QtQuick 2.8 

Text {
    property int index
    text: "Line " + index
}

 问题描述:

ListView 在每次迭代时将 0、1、2 等分配给变量 index。但是,因为我将它分配给一个属性,所以这个变量被隐藏了,我无法访问它。

如果我从Reusable.qml 中删除property int indexListView 可以工作,但在 ListView 之外使用Reusable 将不再工作。

有没有办法分配index: index

(我可以重命名有效的属性,但我想避免这种情况。)

【问题讨论】:

    标签: qml qtquick2 shadowing


    【解决方案1】:

    您可以通过model 前缀寻址模型相关数据。

    ListView {
        model: 3
    
        delegate: Reusable { index: model.index }
    }
    

    即使没有歧义,我的建议也是这样做,以提高可读性。 IE。阅读代码的开发人员可以立即看到哪些数据是本地属性,哪些数据是由模型提供的。

    【讨论】:

    • 这正是我想要的! QML 对我来说仍然感觉有点神秘,没有明显的方法来检测这些东西。 It is documented, but not easy to find.
    • @GeorgSchölly 是的,不幸的是,这种方法并未在整个文档和示例中使用:/
    猜你喜欢
    • 1970-01-01
    • 2018-05-22
    • 2011-01-12
    • 1970-01-01
    • 1970-01-01
    • 2010-09-23
    • 1970-01-01
    • 2016-06-30
    • 1970-01-01
    相关资源
    最近更新 更多