如何在QML中为具有相同名称的属性分配上下文变量?

Geo*_*lly 2 shadowing qml qtquick2

这是以下代码的结果:

第1234行,第0行,第0行,第0行

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
        }   
    }   
}
Run Code Online (Sandbox Code Playgroud)

Reusable.qml

import QtQuick 2.8 

Text {
    property int index
    text: "Line " + index
}
Run Code Online (Sandbox Code Playgroud)

 问题描述:

ListView受让人0,1,2,等等到可变index在每个迭代上.但是,因为我将其分配给属性,所以此变量被遮蔽,我无法访问它.

如果我删除property int indexReusable.qmlListView作品,但使用ReusableListView控件之外不工作了.

有没有办法分配index: index

(我可以重命名可以使用的属性,但我想避免这种情况.)

Kev*_*mer 5

您可以通过model前缀解决模型相关数据.

ListView {
    model: 3

    delegate: Reusable { index: model.index }
}
Run Code Online (Sandbox Code Playgroud)

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

  • @GeorgSchölly 是的,不幸的是,在整个文档和示例中并未使用这种方法:/ (2认同)