Search code examples
qtqmldelegatesroleslistmodel

QML, GridView delegate: ReferenceError: `<variable_name>` is not defined


I am struggling with it a bit so far, but couldn't find an answer. Here is the core situation.

I have a GridView with ListModel:

GridView {
    id: shapeSidePos
    ...
    model: shapeSidePosList
                
    delegate: ButtonIcon {
        style: ButtonIcon.Styles.Parallel
        icon: path
        ...
        }

    ListModel {
        id: shapeSidePosList
        ListElement { path: "../../images/shape_side_positioning_base.png" }
        ListElement { path: "../../images/shape_side_positioning_right.png" }
        ...
    }
}

And in a runtime I get error:

ReferenceError: path is not defined

The thing is, when I have used e.g. Rectangle instead of ButtonIcon, everything worked fine! Accessing elements with model.path did not work either. In ButtonIcon, icon is defined so:

property alias icon: buttonIcon.source

where buttonIcon is an image with MouseArea.

Been searching through web, found some tricks with JS but that makes things complicated and many developers may use this code later. It would be problematic for them. However, I can access the right path while referring directly to an index:

icon: shapeSidePosList.get(0).path

I tried packing delegate into Component, tried DelegateModel, nothing has given the expected result.

I have no idea what is going on,

I would be very thankful for any help provided.


Solution

  • @iam_peter wrote:

    You could try to enforce the path property in the delegate with the required keyword like shown here https://doc.qt.io/qt-6/qtquick-modelviewsdata-modelview.html#view-delegates and see if it yields any other errors.

    I have added a required property to a delegate:

        delegate: ButtonIcon {
            required property var path // <-- this
            required property int index // <-- and this
    
            style: ButtonIcon.Styles.Parallel
            icon: path
            ...
            }
    

    and it worked. Thank you very much!

    Update

    The reason has been found. @GrecKo has explained here https://forum.qt.io/topic/141689/qml-gridview-delegate-referenceerror-variable_name-is-not-defined/4:

    The reason is most likely because ButtonIcon has a required property itself. When a delegate has one it doesn't provide model roles as context properties anymore but only set those corresponding to explicit required properties.

    And the ButtonIcon had a required property indeed.