这是以下代码的结果:

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

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
        }
    }
}

可重用

import QtQuick 2.8

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

问题描述:
ListView在每次迭代中将0、1、2等分配给变量index。但是,由于我将其分配给属性,因此该变量被遮盖了,因此无法访问它。

如果我从property int index中删除Reusable.qml,则ListView有效,但在ListView之外使用Reusable不再有效。

有没有一种分配index: index的方法?

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

最佳答案

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

ListView {
    model: 3

    delegate: Reusable { index: model.index }
}

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

关于qml - 如何在QML中为具有相同名称的属性分配上下文变量?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42079578/

10-11 22:38
查看更多