0
votes

I am new to Qt/QML. I am learning from QML book, I am trying an example to add / remove an element to simple ListModel. After clicking "Add Item", onClicked method in MouseArea of Rectangle is not getting invoked. OnClicked method of delete is in delegation component is working fine.

Here is the code

import QtQuick 2.9
import QtQuick.Window 2.3

Window {
    visible: true
    width: 480
    height: 300
    title: qsTr("Add / Remove")
    color: "blue"

    //ListModel
    ListModel{
        id: lmodel
        ListElement {number: 0}
        ListElement {number: 1}
        ListElement {number: 2}
        ListElement {number: 3}
        ListElement {number: 4}
        ListElement {number: 5}
    }

    // Add button
    Rectangle{
        anchors.left: parent.left
        anchors.right: parent.right
        anchors.bottom: parent.bottom
        anchors.margins: 20
        height: 40
        color: "#00ff00"
        border.color: Qt.lighter(color, 1.1)

        Text {
            anchors.centerIn: parent
            text: "Add Item"
        }

        MouseArea{
            anchors.fill: parent // Edit1
            onClicked: { // this Method is not getting called
                console.log(" add clicked");
                lmodel.append({"number": ++parent.count});
            }
        }

        property int count: 5
    }

    //GridView
    GridView{
        anchors.fill: parent
        anchors.margins: 20
        clip: true
        model: lmodel

        cellHeight: 45
        cellWidth: 45
        delegate: del

    }

    //delegate
    Component{
        id: del
        Rectangle{
            id: wrapper
            width: 40
            height: 40
            color: "yellow"
            Text {
                text: number
                anchors.centerIn: parent
            }
            MouseArea{
                anchors.fill: parent
                onClicked: {
                    console.log(" num clicked");
                    lmodel.remove(index);
                }
            }
        }
    }
}
1

1 Answers

2
votes

You are anchoring MouseArea to ListModel

anchors.fill: lmodel

Second problem: GridView overlaps MouseArea. Try to disable it (just to ensure)

GridView{
    enabled: false