QML - ListView 项目,点击时显示菜单

QML - ListView item which displays a menu on tap

我正在寻找有关在用户点击列表项时在列表项下方显示菜单的一些提示和指示。

如果我有这样的 ListModel:

ListModel {
    ListElement {
        name: "Bill Smith"
        number: "555 3264"
    }
    ListElement {
        name: "John Brown"
        number: "555 8426"
    }
    ListElement {
        name: "Sam Wise"
        number: "555 0473"
    }
}

然后像这样的 ListView:

Rectangle {
    width: 180; height: 200

    Component {
        id: contactDelegate
        Item {
            width: 180; height: 40
            Column {
                Text { text: '<b>Name:</b> ' + name }
                Text { text: '<b>Number:</b> ' + number }
            }
        }
    }

    ListView {
        anchors.fill: parent
        model: ContactModel {}
        delegate: contactDelegate
        highlight: Rectangle { color: "lightsteelblue"; radius: 5 }
        focus: true
    }
}

然后当用户点击我要显示菜单的项目时:

Menu {
    id: menu
    MenuItem { text: "item1" }
    MenuItem { text: "item2"; }
    MenuItem { text: "item3"; }
}

查看其他一些 QML 示例,我发现了一些添加 MouseArea 并根据 Window 定位菜单的代码 - 菜单高度和宽度:

MouseArea {
    anchors.fill: parent
    onClicked: {
        menu.x = (window.width - menu.width) / 2
        menu.y = (window.height - menu.height) / 2
        menu.open();
    }
}

但是我正在努力让它工作,任何人都可以指出我正确的方向吗?

如果确定了Menu的父级是ListView,那么只需要通过mapToItem:

确定按下的item的相对位置即可
Rectangle {
    width: 180; height: 200

    Component {
        id: contactDelegate
        Item {
            width: 180; height: 40
            Column {
                Text { text: '<b>Name:</b> ' + name }
                Text { text: '<b>Number:</b> ' + number }
            }

            MouseArea{
                anchors.fill: parent
                onClicked:  {
                    var pos = mapToItem(listView, 0, height)
                    menu.x = pos.x
                    menu.y = pos.y
                    menu.open()
                }
            }
        }
    }

    ListView {
        id: listView
        objectName: "list"
        anchors.fill: parent
        model: ContactModel{}
        delegate: contactDelegate
        focus: true

        Menu {
            id: menu
            MenuItem { text: "item1" }
            MenuItem { text: "item2"; }
            MenuItem { text: "item3"; }
        }

    }
}

完整的示例可以在下面link.

中找到