Georg Schölly
Georg Schölly

Reputation: 126085

How to assign a context-variable to a property with the same name in QML?

This is the result of the following code:

Line 1234, Line 0, Line 0, Line 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
        }   
    }   
}

Reusable.qml

import QtQuick 2.8 

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

 Problem description:

The ListView assigns 0, 1, 2, etc. to the variable index on every iteration. However, because I am assigning this to a property, this variable is shadowed and I cannot access it.

If I remove property int index from Reusable.qml, the ListView works, but using Reusable outside of the ListView does not work anymore.

Is there a way to assign index: index?

(I could rename the property which would work, but I would like to avoid that.)

Upvotes: 3

Views: 1133

Answers (1)

Kevin Krammer
Kevin Krammer

Reputation: 5207

You can address the model related data through a model prefix.

ListView {
    model: 3

    delegate: Reusable { index: model.index }
}

My recommendation would to do that even if there is no ambiguity, as means to readability. I.e. a developer reading the code can immediately see which data is a local property and which data is provided by the model.

Upvotes: 7

Related Questions